// datatablesSimple

"use strict";

//updateDatabase(dbs[j]).then(function (data) {
//    insertStringTo(name, 'fa-check');
//    console.log(data);
//}).catch(function (err) {
//    insertStringTo(name, 'fa-times');

//    // Run this when promise was rejected via reject()
//    console.log(err);
//});
//const updateDatabase = (id) => {
//    return new Promise(function (resolve, reject) {
//        $.ajax({
//            url: window.urls.ensureOtherDatabaseUpdate,
//            method: 'Get',
//            data: { id },
//            success: function (data) {
//                resolve(data); // Resolve promise and go to then()
//            },
//            error: function (err) {
//                reject(err); // Reject the promise and go to catch()
//            }
//        });
//    });
//}

const materialLoadingElement = $("#materialLoading");

function showLoading() {
    materialLoadingElement.addClass('show');
    materialLoadingElement.removeClass('hide');
}

function hideLoading() {
    materialLoadingElement.addClass('hide');
    materialLoadingElement.removeClass('show');
}

let detailsTable;
let historyTable;

const index = function () {
    const table = document.getElementById('factor-table');
    let datatable;
    let toolbarBase;
    let timeout;

    let toolbarSelected;
    let selectedCount;
    const modalElement = document.getElementById('modal_change');
    const modalFactorDetailsElement = document.getElementById('factorDetails-modal');
    const modalFactorDetails = new bootstrap.Modal(modalFactorDetailsElement);
    const modalMessageElement = document.getElementById('modal_message');
    const modalForm = modalElement.querySelector('#modal_change_form');
    const modal = new bootstrap.Modal(modalElement);
    const modalResultElement = document.getElementById('modal_result');
    const modalResult = new bootstrap.Modal(modalResultElement);
    const modalMessage = new bootstrap.Modal(modalMessageElement);
    let modalFactorHistoryElement = document.getElementById('factorHistory-modal');
    let modalFactorHistory = new bootstrap.Modal(modalFactorHistoryElement);
    let changingRow;
    let modalShowed = false;
    let validationResults = [];
    let submitting = false;
    let currentDtRequest = null;
    const initTable = () => {
        // const tableRows = table.querySelectorAll('tbody tr');
        // tableRows.forEach(row => {
        //     const dateRow = row.querySelectorAll('td');
        //     const lastLogin = dateRow[3].innerText.toLowerCase(); // Get last login time
        //     let timeCount = 0;
        //     let timeFormat = 'minutes';
        //
        //     // Determine date & time format -- add more formats when necessary
        //     if (lastLogin.includes('yesterday')) {
        //         timeCount = 1;
        //         timeFormat = 'days';
        //     } else if (lastLogin.includes('mins')) {
        //         timeCount = parseInt(lastLogin.replace(/\D/g, ''));
        //         timeFormat = 'minutes';
        //     } else if (lastLogin.includes('hours')) {
        //         timeCount = parseInt(lastLogin.replace(/\D/g, ''));
        //         timeFormat = 'hours';
        //     } else if (lastLogin.includes('days')) {
        //         timeCount = parseInt(lastLogin.replace(/\D/g, ''));
        //         timeFormat = 'days';
        //     } else if (lastLogin.includes('weeks')) {
        //         timeCount = parseInt(lastLogin.replace(/\D/g, ''));
        //         timeFormat = 'weeks';
        //     }
        //
        //     // Subtract date/time from today -- more info on moment datetime subtraction: https://momentjs.com/docs/#/durations/subtract/
        //     const realDate = moment().subtract(timeCount, timeFormat).format();
        //
        //     // Insert real date to last login attribute
        //     dateRow[3].setAttribute('data-order', realDate);
        //
        //     // Set real date for joined column
        //     const joinedDate = moment(dateRow[5].innerHTML, "DD MMM YYYY, LT").format(); // select date from 5th column in table
        //     dateRow[5].setAttribute('data-order', joinedDate);
        // });

        // Init datatable --- more info on datatables: https://datatables.net/manual/
        datatable = $(table).DataTable({
            language: {
                url: '../media/fa.json'
            },
            //-------------Scroller
            // ajax: function (data, callback, settings) {
            //
            //     $.ajax({
            //         url: "?handler=FactorsListScroller",
            //         type: "POST",
            //         datatype: "json",
            //         headers: {"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
            //         data: {
            //              // startDate: $('#fromDate').val(),
            //              // endDate: $('#toDate').val(),
            //             // visitor: document.querySelector('#visitor-selector').value.trim() ?? '',
            //             // customer: document.querySelector('#customer-selector').value.trim() ?? '',
            //             // user: document.querySelector('#user-selector').value.trim() ?? '',
            //             // azMablaghInput: document.querySelector('#AzMablaghInput').value.trim(),
            //             // taMablaghInput: document.querySelector('#TaMablaghInput').value.trim(),
            //             // idFactor: document.querySelector('#factorNumberInput').value.trim() ?? '',
            //             // profile: document.querySelector('[data-filter="profile"]') ?? '',
            //             // strSubject: document.querySelector('#factorNumberInput').value.trim() ?? '',
            //             //officialFactor: document.querySelector('#officialFactor').checked,
            //         },
            //         success: function (obj) {
            //             // what is being sent back from the server (if no error)
            //             // console.log(JSON.parse(inData));
            //             //const obj = JSON.parse(inData);
            //             validationResults = [];
            //             for (let i = 0; i < obj.data.length; i++) {
            //                 validationResults.push({
            //                     id: obj.data[i].idFactor,
            //                     messages: obj.data[i].validationResult.errors
            //                 });
            //             }
            //             setTimeout(() => {
            //                 callback({
            //                     draw: data.draw,
            //                     data: obj.data,
            //                     recordsTotal: obj.recordsTotal,
            //                     recordsFiltered: obj.recordsTotal
            //                 });
            //             }, 150);
            //         },
            //         error: function (err, status) {
            //             // what error is seen(it could be either server side or client side.
            //             console.log(err);
            //         },
            //     });
            //
            // },
            //-------------Pagination
            ajax: {
                url: "?handler=FactorsList",
                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));
                    console.time('dataFilter');
                    const obj = JSON.parse(inData);
                    validationResults = [];
                    for (let i = 0; i < obj.data.length; i++) {
                        validationResults.push({
                            id: obj.data[i].idFactor,
                            messages: obj.data[i].validationResult.errors
                        });
                    }
                    console.timeEnd('dataFilter');
                    return inData;
                },
                error: function (err, status) {
                    // what error is seen(it could be either server side or client side.
                    console.log(err);
                },
            },
            deferRender: true,
            stateSave: false,
            autoWidth: true,
            processing: true,
            pageLength: 100,
            serverSide: true,
            // scroller: true,
            scrollY: "500px",
            scrollX: true,
            scrollCollapse: true,
            fixedHeader: true,
            fixedColumns: {
                left: 2
            },
            filter: true,
            columnDefs: [
                { orderable: false, targets: 0 },
                { orderable: false, targets: 1 },

                {
                    targets: 2,
                    createdCell: function (td, cellData, rowData, row, col) {
                        let exist = rowData['exist'];
                        if (!exist) {
                            $(td.closest('tr')).css('background', '#e4612eff');
                        } else {
                            if (rowData['taxId']) {
                                //sent before
                                $(td.closest('tr')).css('background', '#A7DF94');
                            }
                        }
                        cellData = rowData['validationResult'];
                        if (cellData['errors'].length === 0) {
                            //$(td.closest('tr')).css('color', '#66CC87');
                            $(td).css('color', '#66CC87');
                        } else {
                            //$(td.closest('tr')).css('color', '#FF6D60');
                            $(td).css('color', '#FF6D60');

                        }
                    }
                }

            ],
            columns: [
                {
                    orderable: false,
                    defaultContent: `
                        <div class="form-check form-check-sm">
                                        <input class="form-check-input" style="background-color:cadetblue;" type="checkbox" value="1"/>
                                    </div>`
                },
                {
                    data: null,
                    defaultContent: ``,
                    autoWidth: true,
                    orderable: false,
                    searchable: false,
                    render: function (data, type, row, meta) {
                        return `

<div>
<button type="button"  class="btn btn-sm btn-icon btn-color-primary btn-active-light-primary  modal-history-link" data-bs-toggle="tooltip" data-bs-placement="top" title="سابقه ارسال" >
<!--begin::Svg Icon | path: icons/duotune/arrows/arr095.svg-->
<span class="svg-icon svg-icon-4 svg-icon-gray-800 ms-1">
<svg viewBox="0 0 1024 1024" class="icon" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="#000000" data-darkreader-inline-fill="" style="--darkreader-inline-fill: #000000;"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"><path d="M512 1024C229.7 1024 0 794.3 0 512S229.7 0 512 0s512 229.7 512 512-229.7 512-512 512z m0-938.7C276.7 85.3 85.3 276.7 85.3 512S276.7 938.7 512 938.7 938.7 747.3 938.7 512 747.3 85.3 512 85.3z" fill="#3688FF" data-darkreader-inline-fill="" style="--darkreader-inline-fill: #0046ac;"></path><path d="M640 682.7c-9.6 0-19.3-3.2-27.3-9.9l-128-106.7c-9.7-8.1-15.4-20.1-15.4-32.8V384c0-23.6 19.1-42.7 42.7-42.7s42.7 19.1 42.7 42.7v129.4l112.6 93.9c18.1 15.1 20.5 42 5.5 60.1-8.5 10-20.6 15.3-32.8 15.3z" fill="#5F6379" data-darkreader-inline-fill="" style="--darkreader-inline-fill: #4c4f61;"></path></g></svg>
</span>
<!--end::Svg Icon--></button>

<button type="button" class="btn btn-sm btn-icon btn-color-primary btn-active-light-primary modal-details-link" data-kt-menu-trigger="click" data-kt-menu-placement="bottom-end" data-bs-toggle="tooltip" data-bs-placement="top" title="اقلام فاکتور" >
<!--begin::Svg Icon | path: icons/duotune/general/gen024.svg-->
<span class="svg-icon svg-icon-2">
<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" viewBox="0 0 24 24">
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<rect x="5" y="5" width="5" height="5" rx="1" fill="currentColor"></rect>
<rect x="14" y="5" width="5" height="5" rx="1" fill="currentColor" opacity="0.3"></rect>
<rect x="5" y="14" width="5" height="5" rx="1" fill="currentColor" opacity="0.3"></rect>
<rect x="14" y="14" width="5" height="5" rx="1" fill="currentColor" opacity="0.3"></rect>
</g>
</svg>
</span>
<!--end::Svg Icon-->
</button>
<button type="button" class="btn btn-sm btn-icon btn-color-primary btn-active-light-primary modal-status-link" data-kt-menu-trigger="click" data-kt-menu-placement="bottom-end" data-bs-toggle="tooltip" data-bs-placement="top" title="وضعیت فاکتور"  >
<!--begin::Svg Icon | path: icons/duotune/general/gen024.svg-->
<span class="svg-icon svg-icon-2">
<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M3.35288 15.0496L2.6227 15.2209L3.35288 15.0496ZM3.35288 8.95043L2.6227 8.77915L3.35288 8.95043ZM20.6471 8.95044L19.9169 9.12171L20.6471 8.95044ZM20.6471 15.0496L19.9169 14.8783L20.6471 15.0496ZM15.0496 20.6471L14.8783 19.9169L15.0496 20.6471ZM8.95044 20.6471L8.77916 21.3773L8.95044 20.6471ZM8.95043 3.35288L8.77916 2.6227L8.95043 3.35288ZM15.0496 3.35288L14.8783 4.08306L15.0496 3.35288ZM4.08306 14.8783C3.63898 12.9851 3.63898 11.0149 4.08306 9.12171L2.6227 8.77915C2.12577 10.8976 2.12577 13.1024 2.6227 15.2209L4.08306 14.8783ZM19.9169 9.12171C20.361 11.0149 20.361 12.9851 19.9169 14.8783L21.3773 15.2208C21.8742 13.1024 21.8742 10.8976 21.3773 8.77916L19.9169 9.12171ZM14.8783 19.9169C12.9851 20.361 11.0149 20.361 9.12171 19.9169L8.77916 21.3773C10.8976 21.8742 13.1024 21.8742 15.2208 21.3773L14.8783 19.9169ZM9.12171 4.08306C11.0149 3.63898 12.9851 3.63898 14.8783 4.08306L15.2208 2.6227C13.1024 2.12577 10.8976 2.12577 8.77916 2.6227L9.12171 4.08306ZM9.12171 19.9169C6.62161 19.3305 4.6695 17.3784 4.08306 14.8783L2.6227 15.2209C3.33924 18.2756 5.72441 20.6608 8.77916 21.3773L9.12171 19.9169ZM15.2208 21.3773C18.2756 20.6608 20.6608 18.2756 21.3773 15.2208L19.9169 14.8783C19.3305 17.3784 17.3784 19.3305 14.8783 19.9169L15.2208 21.3773ZM14.8783 4.08306C17.3784 4.6695 19.3305 6.62161 19.9169 9.12171L21.3773 8.77916C20.6608 5.72441 18.2756 3.33924 15.2208 2.6227L14.8783 4.08306ZM8.77916 2.6227C5.72441 3.33924 3.33924 5.72441 2.6227 8.77915L4.08306 9.12171C4.6695 6.6216 6.62161 4.6695 9.12171 4.08306L8.77916 2.6227Z" fill="#0095FF" data-darkreader-inline-fill="" style="--darkreader-inline-fill: #0077cc;"></path> <path d="M2.6227 15.2209C2.71729 15.6241 3.12089 15.8743 3.52416 15.7798C3.92742 15.6852 4.17765 15.2816 4.08306 14.8783L2.6227 15.2209ZM3.35288 8.95043L2.6227 8.77915L3.35288 8.95043ZM20.6471 8.95044L19.9169 9.12171L20.6471 8.95044ZM20.6471 15.0496L19.9169 14.8783L20.6471 15.0496ZM14.8783 19.9169C14.475 20.0115 14.2248 20.4151 14.3194 20.8184C14.414 21.2217 14.8176 21.4719 15.2208 21.3773L14.8783 19.9169ZM8.95043 3.35288L8.77916 2.6227L8.95043 3.35288ZM15.0496 3.35288L14.8783 4.08306L15.0496 3.35288ZM4.08306 14.8783C3.63898 12.9851 3.63898 11.0149 4.08306 9.12171L2.6227 8.77915C2.12577 10.8976 2.12577 13.1024 2.6227 15.2209L4.08306 14.8783ZM19.9169 9.12171C20.361 11.0149 20.361 12.9851 19.9169 14.8783L21.3773 15.2208C21.8742 13.1024 21.8742 10.8976 21.3773 8.77916L19.9169 9.12171ZM9.12171 4.08306C11.0149 3.63898 12.9851 3.63898 14.8783 4.08306L15.2208 2.6227C13.1024 2.12577 10.8976 2.12577 8.77916 2.6227L9.12171 4.08306ZM15.2208 21.3773C18.2756 20.6608 20.6608 18.2756 21.3773 15.2208L19.9169 14.8783C19.3305 17.3784 17.3784 19.3305 14.8783 19.9169L15.2208 21.3773ZM14.8783 4.08306C17.3784 4.6695 19.3305 6.62161 19.9169 9.12171L21.3773 8.77916C20.6608 5.72441 18.2756 3.33924 15.2208 2.6227L14.8783 4.08306ZM8.77916 2.6227C5.72441 3.33924 3.33924 5.72441 2.6227 8.77915L4.08306 9.12171C4.6695 6.6216 6.62161 4.6695 9.12171 4.08306L8.77916 2.6227Z" fill="#363853" data-darkreader-inline-fill="" style="--darkreader-inline-fill: #2b2d42;"></path> <path d="M7.85735 12.2228C7.54946 12.4998 7.5245 12.9741 7.8016 13.2819C8.07869 13.5898 8.55291 13.6148 8.86079 13.3377L7.85735 12.2228ZM10.0656 11.2444L10.5673 11.8018V11.8018L10.0656 11.2444ZM11.627 11.4406L12.2511 11.0245L12.2511 11.0245L11.627 11.4406ZM12.373 12.5595L11.749 12.9755L11.749 12.9755L12.373 12.5595ZM13.9345 12.7557L14.4362 13.3131L13.9345 12.7557ZM16.1427 11.7773C16.4506 11.5002 16.4755 11.026 16.1984 10.7181C15.9214 10.4102 15.4471 10.3853 15.1393 10.6623L16.1427 11.7773ZM13.0746 13.2875L12.9811 14.0317H12.9811L13.0746 13.2875ZM10.9255 10.7125L10.832 11.4567L10.832 11.4567L10.9255 10.7125ZM8.86079 13.3377L10.5673 11.8018L9.56386 10.6869L7.85735 12.2228L8.86079 13.3377ZM11.003 11.8566L11.749 12.9755L12.997 12.1435L12.2511 11.0245L11.003 11.8566ZM14.4362 13.3131L16.1427 11.7773L15.1393 10.6623L13.4327 12.1982L14.4362 13.3131ZM11.749 12.9755C11.8916 13.1894 12.0414 13.4173 12.1919 13.5861C12.3566 13.7708 12.6073 13.9847 12.9811 14.0317L13.1681 12.5434C13.227 12.5508 13.2771 12.5721 13.31 12.5929C13.3361 12.6094 13.3372 12.6167 13.3115 12.5878C13.2857 12.5589 13.2487 12.5118 13.1933 12.4333C13.1383 12.3552 13.0763 12.2623 12.997 12.1435L11.749 12.9755ZM13.4327 12.1982C13.3266 12.2937 13.2435 12.3684 13.1709 12.4305C13.0978 12.4929 13.0503 12.5293 13.0182 12.551C12.9861 12.5726 12.989 12.5658 13.0183 12.5563C13.0554 12.5442 13.1091 12.536 13.1681 12.5434L12.9811 14.0317C13.3549 14.0786 13.6507 13.9334 13.8559 13.7952C14.0436 13.6689 14.2451 13.4851 14.4362 13.3131L13.4327 12.1982ZM10.5673 11.8018C10.6734 11.7063 10.7565 11.6316 10.8292 11.5696C10.9023 11.5072 10.9498 11.4707 10.9819 11.4491C11.0139 11.4275 11.0111 11.4343 10.9818 11.4438C10.9447 11.4558 10.8909 11.4641 10.832 11.4567L11.019 9.96837C10.6451 9.92141 10.3493 10.0666 10.1441 10.2048C9.95644 10.3312 9.75493 10.5149 9.56386 10.6869L10.5673 11.8018ZM12.2511 11.0245C12.1085 10.8106 11.9587 10.5828 11.8081 10.4139C11.6435 10.2292 11.3928 10.0153 11.019 9.96837L10.832 11.4567C10.773 11.4493 10.723 11.428 10.69 11.4071C10.664 11.3907 10.6629 11.3834 10.6886 11.4122C10.7144 11.4411 10.7513 11.4882 10.8067 11.5668C10.8618 11.6449 10.9238 11.7378 11.003 11.8566L12.2511 11.0245Z" fill="#0095FF" data-darkreader-inline-fill="" style="--darkreader-inline-fill: #0077cc;"></path> </g></svg>
</span>
<!--end::Svg Icon-->
</button>
</div>
                       `
                    }
                },
                // {data: "id", name: "Id", autoWidth: false},
                {
                    data: "idFactor", name: "IdFactor", autoWidth: false,
                    render: function (data, type, row, meta) {
                        // Render the link
                        if (row["idFactorSell"] > 0)
                            return row["idFactorSell"];
                        return data;
                        //return '<a href="#" style="text-decoration: underline;" class="link-class" data-value="' + row["idFactorSell"] + '">' + row["idFactorSell"] + '</a>';
                        //  return '<a href="#" style="text-decoration: underline;" class="link-class" data-value="' + data + '">' + data + '</a>';

                    }
                },
                {
                    data: "idFactorSell", name: "IdFactorSell", autoWidth: false,
                    render: function (data, type, row, meta) {
                        // Render the link
                        if (row["idFactorSell"] > 0)
                            return row["idFactor"];
                        return row["idFactorSell"];
                    }
                },
                // {data: "successedM", name: "SuccessedM", autoWidth: false},
                { data: "d_date", name: "D_date", autoWidth: false },
                { data: "customInvoiceDate", name: "CustomInvoiceDate", autoWidth: false },
                { data: "taxId", name: "TaxId", autoWidth: false },
                // {data: "date_Sent", name: "DateSent", autoWidth: false},
                // {data: "serialNumber", name: "SerialNumber", autoWidth: false},
                // {data: "uniqueId", name: "uniqueId", autoWidth: false},
                { data: "typeBillText", name: "TypeBill", autoWidth: false },
                { data: "patternText", name: "Pattern", autoWidth: false },
                { data: "subjectBillText", name: "SubjectBill", autoWidth: false },
                // {data: "profileTitle", name: "ProfileTitle", autoWidth: false},
                { data: "kindFroshFactor", name: "KindFroshFactor", autoWidth: true },
                { data: "kind", name: "Kind", autoWidth: true },
                // { data: "monFac", name: "MonFac", autoWidth: false },
                {
                    data: "monFac", name: "MonFac", autoWidth: false,
                    render: function (data, type, full, meta) {
                        return data.toLocaleString();
                    }
                },
                // { data: "discountKol", name: "DiscountKol", autoWidth: true },

                {
                    data: "darsadMon", name: "DarsadMon", autoWidth: true,
                    render: function (data, type, full, meta) {
                        return data.toLocaleString();
                    }
                },

                { data: "mon_After_Discount", name: "Mon_After_Discount", autoWidth: true },
                { data: "monAddedValue", name: "MonAddedValue", autoWidth: true },
                { data: "monPayFac", name: "MonPayFac", autoWidth: true },
                { data: "cash", name: "Cash", autoWidth: false },
                { data: "lendMon", name: "LendMon", autoWidth: false },
                { data: "companyEconomicCode", name: "CompanyEconomicCode", autoWidth: false },
                { data: "pname", name: "pname", autoWidth: false },
                { data: "taxTypeText", name: "TaxTypeText", autoWidth: false },
                { data: "taxType", name: "TaxType", autoWidth: false, visible: false },
                { data: "melliCode", name: "MelliCode", autoWidth: false },
                { data: "economicCode", name: "MelliCode", autoWidth: false },
                { data: "postalCode", name: "PostalCode", autoWidth: false },


            ],
            drawCallback: function (settings) {
                // Initialize the menu after DataTables redraws rows
                //KTMenu.createInstances(); // Initialize Metronic menus
            }
        }).search('').state.clear();
        // datatable.state.clear();
        // datatable.search(''); // clear the global search filter
        // datatable.columns().search(''); // clear the column search filters
        // datatable.order([]); // clear the sorting
        // datatable.draw(); // redraw the table

        $(table).on('xhr.dt', function (e, settings, json, xhr) {
            currentDtRequest = xhr;
        });

        $(table).on('click', '.modal-history-link', function (e) {
            e.preventDefault();
            const value = $(this).data('value');
            //const type = $(this).data('subjectType');
            //const rowIndex = $(this).data('row');
            // var rowData = datatable.row(rowIndex).data();

            let row = $((this).closest('tbody tr'));
            let rowData = datatable.row(row).data();

            // $('#yourDiv').text(JSON.stringify(rowData)).show();

            $('#factorHistory-title').text("سابقه فاکتور: " + rowData["idFactor"]).show();
            $.ajax({
                url: '?handler=FactorHistory',
                data: { idFactor: rowData["idFactor"], kindFactor: rowData["kindFactor"] ?? "" },
                success: function (partialViewHtml) {
                    document.querySelector("#factorHistory-data").innerHTML = partialViewHtml;
                    historyTable = $("#factorHistory-table").DataTable({
                        language: {
                            url: '../media/fa.json'
                        },
                        paging: false,
                        scrollX: true,
                        scrollCollapse: true,
                        fixedHeader: true,
                        fixedColumns: false,
                        scrollY: 300,

                    });
                    modalFactorHistory.show();
                },
                error: function (xhr, status, error) {
                    console.error(error);
                }
            });


        });
        $(table).on('click', '.modal-details-link', function (e) {
            e.preventDefault();
            const value = $(this).data('value');
            const rowIndex = $(this).data('row');
            // var rowData = datatable.row(rowIndex).data();

            // Get the data of the clicked row
            const row = $((this).closest('tbody tr'));
            const rowData = datatable.row(row).data();

            // $('#yourDiv').text(JSON.stringify(rowData)).show();

            $('#factorDetails-title').text("اقلام فاکتور: " + rowData['idFactor']).show();
            const idFactor = rowData.idFactorSell > 0 ? rowData.idFactorSell : rowData.idFactor;
            const idFactorSell = rowData.idFactorSell > 0 ? rowData.idFactorSell : 0;
            $.ajax({
                url: '?handler=FactorDetails',
                data: { idFactor: rowData.idFactor, idFactorSell: rowData.idFactorSell, kindFactor: rowData.kindFactor },
                success: function (partialViewHtml) {
                    // Inject the generated partial view HTML into your desired element
                    // $('#factorDetails').html(partialViewHtml);
                    document.querySelector("#factorDetails").innerHTML = partialViewHtml;
                    detailsTable = $("#factor-details-table").DataTable({
                        language: {
                            url: '../media/fa.json'
                        },
                        scrollX: true,
                        scrollCollapse: true,
                        autoWidth: false,
                        scrollY: 200,
                        columnDefs: [
                            { target: 2, autoWidth: true }
                        ]
                    });
                    handleSearchProductDatatable();
                    modalFactorDetails.show();
                },
                error: function (xhr, status, error) {
                    console.error(error);
                }
            });


        });
        // $(table).on('click', '.modal-status-link', function (e) {

        // });
        $('#factorDetails-modal').on('shown.bs.modal', function () {
            detailsTable.columns.adjust(); // Adjust columns after the modal is visible
        });
        // open modal for editing the row
        $(".factor-card").on('dblclick', 'table tr', function () {
            var rowId = $(this).closest('tr').attr('data-edit-item');
            let row = $(this).closest('tr');
            changingRow = row;
            let data = datatable.row(row).data();
            if (!data)
                return;
            let typeBillOption = new Option(data.typeBillText, data.typeBill, false, true);
            let typeBillSelect = $('#typeBillSelect');

            // Check if the option already exists
            let existingOption = typeBillSelect.find('option[value="' + data.typeBill + '"]');
            if (existingOption.length) {
                // If the option exists, select it and trigger the change event
                existingOption.prop('selected', true);
                typeBillSelect.trigger('change');
            } else {
                // If the option doesn't exist, append it and select it
                typeBillSelect.append(typeBillOption);
                typeBillOption.prop('selected', true);
            }
            let patternOption = new Option(data["patternText"], data["pattern"], false, true);
            let subjectOption = new Option(data["subjectBillText"], data["subjectBill"], false, true);
            let profileOption = new Option(data["profileTitle"], data["settingId"], false, true);
            // Elements
            let factorIdInput = modalForm.querySelector('[name="id"]');
            let taxIdInput = modalForm.querySelector('[name="taxId"]');
            let sellTaxIdElement = modalForm.querySelector('[name="SellTaxId"]');
            let kindFactorInput = modalForm.querySelector('[name="kindFactor"]');
            let factorIdBargashtiInput = modalForm.querySelector('[name="idBargashti"]');
            let invoiceDateInput = modalForm.querySelector('[name="invoice_date"]');
            let factorPatternSelectElement = $('#factorPatternSelect');
            let factorSubjectSelectElement = $('#factorSubjectSelect');
            let profileSelectElement = $('#profileSelect');
            let idTaxResponseElement = $('#idTaxResponse');

            // Check if the pattern option already exists
            let existingPatternOption = factorPatternSelectElement.find('option[value="' + data["pattern"] + '"]');
            if (existingPatternOption.length) {
                // If the option exists, select it and trigger the change event
                existingPatternOption.prop('selected', true);
                factorPatternSelectElement.trigger('change');
            } else {
                // If the option doesn't exist, append it and select it
                factorPatternSelectElement.append(patternOption);
                patternOption.prop('selected', true);
            }

            // Check if the subject option already exists
            let existingSubjectOption = factorSubjectSelectElement.find('option[value="' + data["subjectBill"] + '"]');
            if (existingSubjectOption.length) {
                // If the option exists, select it and trigger the change event
                existingSubjectOption.prop('selected', true);
                factorSubjectSelectElement.trigger('change');
            } else {
                // If the option doesn't exist, append it and select it
                factorSubjectSelectElement.append(subjectOption);
                subjectOption.prop('selected', true);
            }
            let existingProfileOption = profileSelectElement.find('option[value="' + data["settingId"] + '"]');
            if (existingProfileOption.length) {
                // If the option exists, select it and trigger the change event
                existingProfileOption.prop('selected', true);
                profileSelectElement.trigger('change');
            }
            // else {
            //     // If the option doesn't exist, append it and select it
            //     let a = profileSelect.find('option[value="0"]');
            //     a.prop('selected',true);
            //     profileSelect.trigger('change');
            //    
            // }

            // Set the value of the id input field
            factorIdInput.value = data["idFactorSell"] === 0 || data["idFactorSell"] === null ? data.idFactor : data.idFactorSell;
            taxIdInput.value = data.taxId;
            factorIdBargashtiInput.value = data["idFactorSell"] === 0 || data["idFactorSell"] === null ? data.idFactorSell : data.idFactor;
            kindFactorInput.value = data["kindFactor"];
            invoiceDateInput.value = data["customInvoiceDate"];
            idTaxResponseElement.value = data["idTaxResponse"];
            sellTaxIdElement.value = data["irTaxId"];

            modal.show();
        });

        // datatable.buttons(0, null).container().insertAfter($('#button_container'));
        datatable.columns().every(function () {
            const that = this;
            $('[data-filter-table="search"] input').on('keyup change', function () {
                if (that.search() == this.value) {
                    // that.search(this.value).draw();
                }
            });
        });

        // Re-init functions on every table re-draw -- more info: https://datatables.net/reference/event/draw
        datatable.on('draw', function () {
            initToggleToolbar();
            toggleToolbars();
            const links = table.querySelectorAll('tbody .modal-status-link');
            const html = (code, message, cls) => {
                return ` <div class="timeline-label">
                                <div class="timeline-item">
                                    <div class="timeline-label fw-bolder text-gray-800 fs-6">${code}</div>
                                    <!--begin::Badge-->
                                    <div class="timeline-badge">
                                        <i class="fa fa-genderless text-${cls} fs-1"></i>
                                    </div>
                                    <!--end::Badge-->
                                    <!--begin::Text-->
                                    <div class="fw-mormal timeline-content text-muted ps-3">${message}
                                    </div>
                                    <!--end::Text-->
                                </div>
                            </div>`;
            };
            links.forEach(c => {
                c.addEventListener('click', function (e) {
                    const row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    const data = datatable.row(row).data();
                    for (let i = 0; i < validationResults.length; i++) {
                        if (validationResults[i].id == data.idFactor) {

                            let msg = '';

                            if (validationResults[i].messages.length > 0) {
                                for (let j = 0; j < validationResults[i].messages.length; j++) {
                                    msg += html('', validationResults[i].messages[j], 'danger');
                                }

                                $('#message-body').html(msg);
                                modalMessage.show();
                            }
                            break;

                        }
                    }
                });

            });
            // Comment this code because the page will hangs
            //let messagesAll = '';
            //$('#messages_all').html('');
            //for (let i = 0; i < validationResults.length; i++) {
            //    for (let j = 0; j < validationResults[i].messages.length; j++) {
            //        messagesAll += html(validationResults[i].id, validationResults[i].messages[j], 'danger');
            //    }
            //}
            //$('#messages_all').html(messagesAll);
        });
    };
    // Init toggle toolbar
    const initToggleToolbar = () => {
        // Toggle selected action toolbar   
        // Select all checkboxes
        const checkboxes = document.querySelector(".table-responsive")
            .querySelectorAll('[type="checkbox"]');

        // Select elements
        toolbarBase = document.querySelector('[data-card-toolbar="base"]');
        toolbarSelected = document.querySelector('[data-card-toolbar="selected"]');
        selectedCount = document.querySelector('[data-card-toolbar="selected_count"]');

        // Toggle delete selected toolbar
        checkboxes.forEach(c => {
            // Checkbox on click event
            c.addEventListener('click', function () {
                setTimeout(function () {
                    toggleToolbars();
                }, 50);
            });
        });


    };

    // Toggle toolbars
    const toggleToolbars = () => {
        // Select refreshed checkbox DOM elements 
        const allCheckboxes = table.querySelectorAll('tbody [type="checkbox"]');

        // Detect checkboxes state & count
        let checkedState = false;
        let count = 0;

        // Count checked boxes
        allCheckboxes.forEach(c => {
            if (c.checked) {
                checkedState = true;
                count++;
            }
        });

        // Toggle toolbars
        if (checkedState) {
            selectedCount.innerHTML = count;
            toolbarBase.classList.add('d-none');
            toolbarSelected.classList.remove('d-none');
            const elementCollapse = document.getElementById('kt_advanced_search_form');
            if (elementCollapse.classList.contains('show')) {
                elementCollapse.classList.toggle('show');
                elementCollapse.blur();
            }
        } else {
            toolbarBase.classList.remove('d-none');
            toolbarSelected.classList.add('d-none');
        }
    };
    // Search Datatable --- official docs reference: https://datatables.net/reference/api/search()
    const handleSearchDatatable = () => {
        const filterSearch = document.querySelector('[data-filter-table="search"]');
        filterSearch.addEventListener('keyup', function (e) {
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                datatable.search(e.target.value).draw();

            }, 800);
        });
    };
    const handleSearchProductDatatable = () => {
        const filterSearch = document.querySelector('[data-filter-table="search-product"]');
        filterSearch.addEventListener('keyup', function (e) {
            detailsTable.search(e.target.value).draw();
        });
    };
    const initComponents = () => {
        //datepicker
        // const dtp1Instance = new mds.MdsPersianDateTimePicker(document.getElementById('datepicker'), {
        //     targetDateSelector: '[data-name="datepicker"]',
        //     isGregorian:false,
        //     persianNumber:true,
        //     rangeSelector:true
        // });


        jalaliDatepicker.startWatch({ time: true });

        // $('#visitor-selector').select2({
        //     ajax: {
        //         url: '?handler=getVisitor',
        //         processResults: function (data) {
        //             return {
        //                 results: data
        //             };
        //         }
        //     }
        // })
        Inputmask({
            mask: "9999/99/99",
            placeholder: "YYYY/MM/DD",
            definitions: {
                'Y': { validator: "[1-2]", cardinality: 1 },
                'M': { validator: "0[1-9]|1[0-2]", cardinality: 2 },
                'D': { validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2 },
                'H': { validator: "[01][0-9]|2[0-3]", cardinality: 2 },
                'm': { validator: "[0-5][0-9]", cardinality: 2 },
                's': { validator: "[0-5][0-9]", cardinality: 2 }
            }
        }).mask("#fromDate");
        Inputmask({
            mask: "9999/99/99",
            placeholder: "YYYY/MM/DD",
            definitions: {
                'Y': { validator: "[1-2]", cardinality: 1 },
                'M': { validator: "0[1-9]|1[0-2]", cardinality: 2 },
                'D': { validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2 },
                'H': { validator: "[01][0-9]|2[0-3]", cardinality: 2 },
                'm': { validator: "[0-5][0-9]", cardinality: 2 },
                's': { validator: "[0-5][0-9]", cardinality: 2 }
            }
        }).mask("#toDate");
        const date = new Date();
        const options = { year: 'numeric', month: '2-digit', day: '2-digit', numberingSystem: 'latn' }; // numberingSystem: 'persian' 
        const shamsiDate = date.toLocaleDateString('fa-IR', options);

        const firstDayShamsiDate = date.toLocaleDateString('fa-IR', options);

        const [shamsiyear, shamsimonth, shamsiday] = shamsiDate.split('/');
        const gregorianDate = new Date(`${shamsiyear}-${shamsimonth}-${shamsiday}`);
        gregorianDate.setMonth(gregorianDate.getMonth() + 2);

        const monthDiff = 0; // difference in months
        const year = date.getFullYear();
        const month = date.getMonth() + monthDiff;
        const firstDay = new Date(year, month - 3, 1);
        const lastDay = new Date(year, month, 0);
        const today = new Date();
        today.setMonth(today.getMonth() - 3);
        //$('#fromDate').val(shamsiyear+'/01/01');
        $('#fromDate').val(today.toLocaleDateString('fa-IR', options));
        //$('#toDate').val(shamsiyear+'/12/29');
        $('#toDate').val(date.toLocaleDateString('fa-IR', options));
    };
    const handlers = () => {

        const filterStatus = document.querySelector('[data-filter="profile"]');
        $(filterStatus).on('change', e => {
            let value = e.target.value;
            if (value === 'all') {
                value = '';
            }
            datatable.column(10).search(value);

        });
        const filterSubject = document.querySelector('[data-filter="subject"]');
        $(filterSubject).on('change', e => {
            let value = e.target.value;
            if (value === 'all') {
                value = '';
            }
            datatable.column(11).search(value);

        });
        const filterZarinType = document.querySelector('[data-filter="zarinTypeFilter"]');
        $(filterZarinType).on('change', e => {
            let value = e.target.value;
            if (!value)
                return;
            if (value === "16") {
                $('#selltaxiddiv').show();
            } else {
                $('#selltaxiddiv').hide();
            }
            datatable.column(13).search(value).draw();


        });
        $('#btnFilter').click(function () {
            datatable.columns(1).search($('#fromDate').val());
            datatable.columns(2).search($('#toDate').val());
            datatable.columns(3).search(document.querySelector('#visitor-selector').value.trim() ?? '');
            datatable.columns(4).search(document.querySelector('#customer-selector').value.trim() ?? '');
            datatable.columns(5).search(document.querySelector('#user-selector').value.trim() ?? '');
            datatable.columns(6).search(document.querySelector('#AzMablaghInput').value.trim() ?? 0);
            datatable.columns(7).search(document.querySelector('#TaMablaghInput').value.trim() ?? 0);
            datatable.columns(8).search(document.querySelector('#factorNumberInput').value.trim() ?? '');
            datatable.columns(9).search(document.querySelector('#officialFactor').checked);
            datatable.columns(12).search(document.querySelector('#noVatInvoiceCheck').checked);

            if (document.querySelector('[data-filter-table="search"]').value == '')
                datatable.search('');
            datatable.draw();
        });
        $('#btnFilter1').click(function () {
            datatable.columns(7).search(document.querySelector('input[name="leaveType"]:checked').value.trim());
            datatable.columns(8).search(document.querySelector('input[name="dateRadio"]:checked').value.trim());
            if ($('#search_checkbox_date').prop('checked')) {
                if ($('#search_start_date').val().trim() === '' && $('#search_end_date').val().trim() == '') {
                    toastr.warning(window.translates.selectDateWarning);
                    return;
                }
                if ($('#search_start_date').val().trim() !== '' && $('#search_end_date').val().trim() !== '') {
                    if ($('#search_start_date').val().trim() > $('#search_end_date').val().trim()) {
                        Swal.fire({
                            text: window.translates.invalidDates,
                            icon: "error",
                            buttonsStyling: false,
                            confirmButtonText: window.translates.ok,
                            customClass: {
                                confirmButton: "btn btn-primary"
                            }
                        });
                        return;
                    }
                }
                datatable.columns(3).search($('#search_start_date').val().trim());
                datatable.columns(4).search($('#search_end_date').val().trim());
            } else {
                datatable.columns(3).search('');
                datatable.columns(4).search('');
            }
            if ($('#search_checkbox_time').prop('checked')) {

                if ($('#search_start_time').val().trim() === '' && $('#search_end_time').val().trim() == '') {
                    toastr.warning(window.translates.selectTimeWarning);
                    return;
                }
                datatable.columns(5).search($('#search_start_time').val().trim());
                datatable.columns(6).search($('#search_end_time').val().trim());
            } else {
                datatable.columns(5).search('');
                datatable.columns(6).search('');
            }
            datatable.draw();
        });
        $('[data-card-toolbar="send_selected"]').click(async function () {
            const $btn = $(this);
            if ($btn.prop('disabled')) {
                return;
            }
            $btn.prop('disabled', true);
            if (!(await confirmAction())) return;
            const checkboxes = table.querySelectorAll('[type="checkbox"]');

            // Select elements
            const deleteSelected = document.querySelector('[data-kt-customer-table-select="delete_selected"]');
            const selectedInvoices = [];
            const backsellIds = [];
            checkboxes.forEach(c => {
                if (c.checked) {
                    const row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    const data = datatable.row(row).data();
                    selectedInvoices.push({
                        idLink: data['idFactor'],
                        id: data['idTaxResponse'],
                        referenceId: data['referenceId'],
                        taxId: data['taxId'],
                        serialNumber: data['taxId'],
                        idFactorSell: data['idFactorSell'],
                        typeLink: data['kindFactor'],
                        subjectBill: data['subjectBill']
                    });
                }
            });
            // var selectedIds = datatable.columns().checkboxes.selected()[0];
            showLoading();

            $.ajax({
                url: '?handler=SendingFactor',
                method: 'POST',
                data: { invoices: selectedInvoices, type: $('[data-filter="zarinTypeFilter"]').val() },
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (response) {
                    const html = (code, message, cls) => {
                        return ` <div class="timeline-label">
                                <div class="timeline-item">
                                    <div class="timeline-label fw-bolder text-gray-800 fs-6">${code}</div>
                                    <div class="timeline-badge">
                                        <i class="fa fa-genderless text-${cls} fs-1"></i>
                                    </div>
                                    <div class="fw-mormal timeline-content text-muted ps-3">${message}
                                    </div>
                                </div>
                            </div>`;
                    };
                    let msg = "";
                    if (response.length > 0) {
                        for (let i = 0; i < response.length; i++) {
                            msg += html(response[i]['factorId'],
                                (response[i]['hasError'] == null || response[i]['hasError'] == '') ? 'ارسال موفق' : response[i]['hasError'],
                                (response[i]['hasError'] == null || response[i]['hasError'] == '') ? 'success' : 'danger');
                        }
                        document.getElementById('result-body').innerHTML = msg;
                        modalResult.show();

                        document.getElementById('btnFilter').click();
                    } else {
                        toastr.warning('پاسخی دریافت نشد');
                    }
                    $btn.prop('disabled', false);
                    hideLoading();
                },
                error: function (x) {
                    console.log(x);
                    hideLoading();
                    $btn.prop('disabled', false);
                    swal.fire({
                        title: 'خطا در ارسال',
                        text: x.responseText,
                        icon: 'error',
                        confirmButtonText: 'باشه',
                        customClass: {
                            confirmButton: "btn fw-bold btn-danger",
                        }
                    });

                }
            });
        });
        // $('#modal_message').on('hidden.bs.modal', function (e) {
        //     document.getElementById('btnFilter').click();
        //   })

        $(modalElement).on('hidden.bs.modal',
            function () {
                modalShowed = false;
            });
        const submitBtn = modalElement.querySelector('#modal_change_submit');
        submitBtn.addEventListener('click', function (e) {
            e.preventDefault();

            const typeBillSelectId = $('#typeBillSelect').select2('data')[0].id;
            const subjectSelectId = $('#factorSubjectSelect').select2('data')[0].id;
            const patternSelectId = $('#factorPatternSelect').select2('data')[0].id;
            const profileSelectId = $('#profileSelect').select2('data')[0].id;

            if (patternSelectId > 0 && subjectSelectId >> 0 && typeBillSelectId > 0 && profileSelectId > 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();
                if (submitting)
                    return;
                submitting = true;

                submitBtn.setAttribute('data-kt-indicator', 'on');
                submitBtn.disabled = true;

                modal.hide();
                modalShowed = false;
                $.ajax({
                    url: '?handler=UpdateBill',
                    method: 'post',
                    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                    data: {
                        taxId: modalForm.querySelector('[name="taxId"]').value,
                        factorId: modalForm.querySelector('[name="id"]').value,
                        idTaxResponse: modalForm.querySelector('[name="idTaxResponse"]').value,
                        idBargashti: modalForm.querySelector('[name="idBargashti"]').value,
                        kindFactor: modalForm.querySelector('[name="kindFactor"]').value,
                        invoiceDate: document.getElementById('invoice_date').value,
                        selltaxId: document.getElementById('selltaxid').value,
                        typeBill: typeBillSelectId,
                        pattern: patternSelectId,
                        subject: subjectSelectId,
                        profile: profileSelectId,
                    },
                    success: function (res) {
                        submitting = false;
                        submitBtn.removeAttribute('data-kt-indicator');
                        submitBtn.disabled = false;
                        if (res == true) {
                            toastr.success('تغییرات اعمال شد');
                            document.getElementById('btnFilter').click();
                        } else
                            toastr.error('عدم ثبت تغییرات');
                    },
                    error: function (err) {
                        submitting = false;
                        submitBtn.removeAttribute('data-kt-indicator');
                        submitBtn.disabled = false;
                        toastr.error(err.responseText);

                    }
                });
                //submit to server
            }
        });
    };

    async function confirmAction() {
        const result = await Swal.fire({
            title: 'آیا از ارسال موارد انتخاب شده اطمینان دارید؟',
            text: "قبل از انتخاب برای ارسال از وضعیت آنها در سامانه مطمئن شوید",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'بله',
            cancelButtonText: 'خیر'
        });
        return result.isConfirmed;
    }

    return {
        // Public functions  
        init: function () {
            if (!table) {
                return;
            }
            initComponents();
            initTable();
            handlers();
            handleSearchDatatable();
        }
    };
}();


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