// var Car_Workshop = client.getTable('Car_Workshop');


// First define the table
var oTableInvoiceComparison = new sap.m.Table({
    growing: true,
    noDataText: oBundle.getText("No_Data"),
    growingTriggerText: oBundle.getText("More"),
    sticky: [sap.m.Sticky.ColumnHeaders, sap.m.Sticky.HeaderToolbar, sap.m.Sticky.InfoToolbar],
    growingThreshold: 25,
    growingScrollToLoad: false,
    
    headerToolbar: new sap.m.Toolbar({
        content: [
            new sap.m.Button({
                text: "Export to Excel",
                icon: "sap-icon://excel-attachment",
                type: "Emphasized",
                press: function() {
                    exportTableToExcel();
                }
            }),
            new sap.m.MenuButton({
                text: "Bulk Upload",
                icon: "sap-icon://database",
                type: "Transparent",
                menu: new sap.m.Menu({
                    items: [
                        new sap.m.MenuItem({
                            text: "Sample Upload",
                            press: function() {
                                window.open("assets/Workshop_Invoice.xlsx", "_blank");
                            }
                        }),
                        new sap.m.MenuItem({
                            text: "Upload Excel",
                            press: function() {
                                attachInvoiceDocument();
                            }
                        })
                    ]
                })
            }),
            new sap.m.Button({
                text: "Reopen Invoice",
                icon:"sap-icon://journey-change",
                type: "Emphasized",
                press: function () {
                    reopenInvoiceDialog();
                }
            }),
            new sap.m.Label({
                text: "",
                design: "Bold",
                // class: "sapUiTinyMarginBegin sapUiTinyMarginEnd"
            }),
            new sap.m.ComboBox({
                width: "200px",
                placeholder: "Select Workshop Name",
                // items: [
                //     new sap.ui.core.Item({ key: "all", text: "All Workshop Names" })
                // ],
                selectionChange: function(oEvent) {
                    var selectedKey = oEvent.getParameter("selectedItem").getKey();
                    var selectedText = oEvent.getParameter("selectedItem").getText();
                    var oBinding = oTableInvoiceComparison.getBinding("items");
               

                    // Find the email button in toolbar
                    var oToolbar = this.getParent();
                    var oEmailButton = null;
                    oToolbar.getContent().forEach(function(control) {
                        if (control instanceof sap.m.Button && control.hasStyleClass("emailButton")) {
                            oEmailButton = control;
                        }
                    });


                    // if (oBinding) {
                    //     if (selectedKey === "all") {
                    //         oBinding.filter(null);
                    //         if (oEmailButton) {
                    //             oEmailButton.setVisible(false);
                    //         }
                            
                    //         // Uncheck all rows and header checkbox when "All" is selected
                    //         var oHeaderCheckBox = oTableInvoiceComparison.getColumns()[0].getHeader();
                    //         oHeaderCheckBox.setSelected(false);
                            
                    //         var aItems = oTableInvoiceComparison.getItems();
                    //         aItems.forEach(function(oItem) {
                    //             oItem.getCells()[0].setSelected(false);
                    //         });
                    //     } else {
                            // var oFilter = new sap.ui.model.Filter("workshop_name", sap.ui.model.FilterOperator.EQ, selectedKey);
                            //                                 oBinding.filter(oFilter);
                            
                            // // Uncheck all rows and header checkbox when filter changes
                            // var oHeaderCheckBox = oTableInvoiceComparison.getColumns()[0].getHeader();
                            // oHeaderCheckBox.setSelected(false);
                            
                            // var aItems = oTableInvoiceComparison.getItems();
                            // aItems.forEach(function(oItem) {
                            //     oItem.getCells()[0].setSelected(false);
                            // });
                            
                            if (oEmailButton) {
                                var email = workshopEmailMap.get(selectedText);
                                if (email) {
                                    oEmailButton.setText(email);
                                    oEmailButton.setVisible(true);
                                                        } else {
                                    oEmailButton.setVisible(false);
                                }
                            }

                            getInvoiceCompareData(selectedKey,oTableInvoiceComparison);//Selected Workshop Name
                        }
                    // }
                // }
            }),
            new sap.m.Button({
                text: "",
                type: "Transparent",
                tooltip: "Workshop Email",
                visible: false,
                enabled: true,
                press: function() {
                    var selectedItems = oTableInvoiceComparison.getItems().filter(function(item) {
                        return item.getCells()[0].getSelected();
                    });

                    if (selectedItems.length === 0) {
                        sap.m.MessageBox.error("Please select at least one workorder before sending email.");
                        return;
                    }

                    sap.m.MessageBox.confirm(
                        "Do you want to send email for selected workorders?",
                        {
                            onClose: function(oAction) {
                                if (oAction === sap.m.MessageBox.Action.OK) {
                                    var busyDialog = new sap.m.BusyDialog({
                                        title: "Sending Email",
                                        text: "Please wait..."
                                    });
                                    busyDialog.open();

                                    // Prepare mismatched items data
                                    var mismatchedItems = selectedItems.map(function(item) {
                                        var data = item.getBindingContext().getObject();
                                        var approved = parseFloat(data.workshop_cost) || 0;
                                        var invoiced = parseFloat(data.invoice_amount) || 0;
                                        var difference = (invoiced - approved).toFixed(2);
                                        
                                        return {
                                            workshop_group: data.ws_group_name,
                                            workshop_name: data.workshop_name,
                                            workorder_no: data.wo_number,
                                            license_plate: data.license_number,
                                            approved_amount: data.workshop_cost,
                                            invoice_amount: data.invoice_amount,
                                            invoice_number: data.invoice_number,
                                            rental_company: data.rental_company_name || "-",
                                            leasing_company: data.leasing_company_name || "-",
                                            difference: difference,
                                            status: approved === invoiced ? "Matched" : "Discrepancy"
                                        };
                                    });

                                    // Call your API
                                    $.ajax({
                                        url: `${jrs_go_api_url_name}/integration/email/sendInvoiceDiscrepancy`,
                                        method: 'POST',
                                        headers: {
                                            'X-API-Key': jrs_go_api_key,
                                            'Content-Type': 'application/json'
                                        },
                                        data: JSON.stringify({
                                            to: this.getText(), // Email from button
                                            mismatched_items: mismatchedItems
                                        }),
                                        success: function(response) {
                                            busyDialog.close();
                                            sap.m.MessageToast.show("Email sent successfully!");
                                        },
                                        error: function(xhr, status, error) {
                                            busyDialog.close();
                                            console.error("Email sending failed:", error);
                                            sap.m.MessageBox.error(
                                                xhr.responseJSON?.message || 
                                                "Failed to send email. Please try again."
                                            );
                                        }
                                    });
                                }
                            }.bind(this)
                        }
                    );
                }
            }).addStyleClass("emailButton"),
            new sap.m.SearchField({
                width: "250px",
                placeholder: "Search...",
                liveChange: function(oEvent) {
                    var sQuery = oEvent.getParameter("newValue");
                    var oFilter = null;
                    if (sQuery) {
                        var aFilters = [
                            new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, sQuery),
                            new sap.ui.model.Filter("ws_group_name", sap.ui.model.FilterOperator.Contains, sQuery),
                            new sap.ui.model.Filter("ws_group_number", sap.ui.model.FilterOperator.Contains, sQuery),
                            new sap.ui.model.Filter("workshop_name", sap.ui.model.FilterOperator.Contains, sQuery),
                            new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.Contains, sQuery),
                            new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, sQuery),
                            new sap.ui.model.Filter("invoice_number", sap.ui.model.FilterOperator.Contains, sQuery),
                            new sap.ui.model.Filter("rental_company_name", sap.ui.model.FilterOperator.Contains, sQuery),
                            new sap.ui.model.Filter("leasing_company_name", sap.ui.model.FilterOperator.Contains, sQuery)
                        ];
                        oFilter = new sap.ui.model.Filter({
                            filters: aFilters,
                            and: false
                        });

                         // Additional logic for external call
                        // if((sQuery.startsWith("4W2") || sQuery.startsWith("2W2")) && sQuery.length > 13) {
                        //     console.log(sQuery)
                        //     setTimeout(function () {
                        //         var items = oTableInvoiceComparison.getItems(); //For All table
                        //         var visibleItems = items.filter(function (item) {
                        //             return item.getVisible(); // Only visible items
                        //         });
                        //         // console.log("hello")
                        //         if (visibleItems.length === 0) {
                        //             busyDialog.open();
                        //             sap.m.MessageToast.show('Getting Data From DB.');
                        //             funGetWorkorderDetailsFromDb(sQuery, 'INVOICECOMPARE');//grabGrnWOJSONArray, oTable4WGrnWO, workorderTemplate,
                        //         }
                        //     }, 300); // Small delay to let filtering apply
                        // }
                    } else {
                        // When search is cleared, uncheck all checkboxes
                        var oHeaderCheckBox = oTableInvoiceComparison.getColumns()[0].getHeader();
                        oHeaderCheckBox.setSelected(false);
                        
                        var aItems = oTableInvoiceComparison.getItems();
                        aItems.forEach(function(oItem) {
                            oItem.getCells()[0].setSelected(false);
                        });
                    }
                    
                                    var oBinding = oTableInvoiceComparison.getBinding("items");
                                    if (oBinding) {
                        oBinding.filter(oFilter);
                                    }
                                }
                            }),
            new sap.m.Button({
                icon: "sap-icon://filter",
                type: "Transparent",
                // class: "sapUiTinyMarginBegin",
                press: function() {
                    clearWsInvoiceFilters();
                    populateWsInvoiceFilterDropdowns();
                    oFilterWsInvoiceDialog.open();
                }
            })
        ]
    }),
    
    columns: [
        new sap.m.Column({
            header: new sap.m.CheckBox({
                select: function (oEvent) {
                    var bSelected = oEvent.getParameter("selected");
                    var aItems = oTableInvoiceComparison.getItems();
                    aItems.forEach(function (oItem) {
                        oItem.getCells()[0].setSelected(bSelected);
                    });
                }
            })
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Workshop Group", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Workshop Name", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Workorder No", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "License Plate", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Approved Amount", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Invoice Amount", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Invoice Number", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Rental Company", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Leasing Company", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Difference", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Status", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Label({ 
                text: "Date", 
                design: sap.m.LabelDesign.Bold,
                wrapping: true,
                width: "100%"
            }),
            width: "auto",
            demandPopin: true,
            minScreenWidth: "Tablet",
            popinDisplay: "Block",
            hAlign: "Begin"
        })
    ]
});

var invoiceComparisonTemplate = new sap.m.ColumnListItem({
    cells: [
        new sap.m.CheckBox(),
        new sap.m.Text({ 
            text: "{ws_group_name}",
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({ 
            text: "{workshop_name}",
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({ 
            text: "{wo_number}",
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({ 
            text: "{license_number}",
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({ 
            text: "{workshop_cost}",
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({ 
            text: "{invoice_amount}",
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({ 
            text: "{invoice_number}",
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({ 
            text: "{rental_company_name}",
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({ 
            text: "{leasing_company_name}",
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({
            text: {
                parts: ["workshop_cost", "invoice_amount"],
                formatter: function(approvedAmt, invoicedAmt) {
                    var approved = parseFloat(approvedAmt) || 0;
                    var invoiced = parseFloat(invoicedAmt) || 0;
                    var difference = invoiced - approved;
                    return difference.toFixed(2);
                }
            },
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({
            text: {
                parts: ["workshop_cost", "invoice_amount"],
                formatter: function(approvedAmt, invoicedAmt) {
                    var approved = parseFloat(approvedAmt) || 0;
                    var invoiced = parseFloat(invoicedAmt) || 0;
                    return approved === invoiced ? "Matched" : "Discrepancy";
                }
            },
            wrapping: true,
            wrappingType: "Hyphenated"
        }),
        new sap.m.Text({ 
            text: "{created_date}",
            wrapping: true,
            wrappingType: "Hyphenated"
        })
    ]
});


// Create the filter dialog with Input fields instead of ComboBoxes
var oFilterWsInvoiceDialog = new sap.m.Dialog({
    title: "Multi Filter Workorder",
    contentWidth: "40%",
    content: [
        new sap.m.VBox({
            width: "100%",
            items: [
                new sap.m.Label({ text: "Workshop Group:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Workshop Group"
                }),
                
                new sap.m.Label({ text: "License Number:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select License Number"
                }),
                
                new sap.m.Label({ text: "Invoice Number:", design: "Bold", required: false }),
                new sap.m.Input({ 
                    width: "94%",
                    placeholder: "Enter Invoice Number"
                }),
                
                new sap.m.Label({ text: "Rental Company:", design: "Bold", required: false }),
                new sap.m.Input({ 
                    width: "94%",
                    placeholder: "Enter Rental Company"
                }),
                
                new sap.m.Label({ text: "Leasing Company:", design: "Bold", required: false }),
                new sap.m.Input({ 
                    width: "94%",
                    placeholder: "Enter Leasing Company"
                }),
                
                new sap.m.Label({ text: "Status Filter:", design: "Bold", required: false }),
                new sap.m.HBox({
                    items: [
                        new sap.m.CheckBox({
                            text: "Discrepancy",
                            select: function(oEvent) {
                                if(oEvent.getParameter("selected")) {
                                    this.getParent().getItems()[1].setSelected(false);
                                }
                            }
                        }).addStyleClass("filterCheckbox"),
                        new sap.m.CheckBox({
                            text: "Matched",
                            select: function(oEvent) {
                                if(oEvent.getParameter("selected")) {
                                    this.getParent().getItems()[0].setSelected(false);
                                }
                            }
                        }).addStyleClass("filterCheckbox")
                    ]
                }).addStyleClass("filterCheckboxContainer")
            ]
        }).addStyleClass("sapUiSmallMargin")
    ],
    buttons: [
        new sap.m.Button({
            icon: "sap-icon://clear-filter",
            text: "Clear Filter",
            press: function() {
                clearWsInvoiceFilters();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://decline",
            text: "Cancel",
            press: function() {
                oFilterWsInvoiceDialog.close();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://filter",
            text: "Apply Filter",
            type: "Emphasized",
            press: function() {
                var aFilters = [];
                
                // Get ComboBoxes (only first two fields now)
                var aComboBoxes = oFilterWsInvoiceDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.ComboBox;
                });
                
                // Get Input fields (last three fields)
                var aInputs = oFilterWsInvoiceDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.Input;
                });
                
                // Get status checkboxes
                var oCheckBoxes = oFilterWsInvoiceDialog.getContent()[0].getItems().slice(-1)[0].getItems();
                var bDiscrepancy = oCheckBoxes[0].getSelected();
                var bMatched = oCheckBoxes[1].getSelected();
                
                // Add status filter if either checkbox is selected
                if (bDiscrepancy || bMatched) {
                    aFilters.push(new sap.ui.model.Filter({
                        path: "",
                        test: function(oItem) {
                            // Access the properties directly from the item
                            var approved = parseFloat(oItem.workshop_cost) || 0;
                            var invoiced = parseFloat(oItem.invoice_amount) || 0;
                            var isMatch = approved === invoiced;
                            return bDiscrepancy ? !isMatch : isMatch;
                        }
                    }));
                }
                
                // Add filters for ComboBox fields (Workshop Group and License Number)
                var comboBoxFields = ["ws_group_name", "license_number"];
                aComboBoxes.forEach(function(oComboBox, index) {
                    var sValue = oComboBox.getSelectedKey();
                    if (sValue) {
                        aFilters.push(new sap.ui.model.Filter(
                            comboBoxFields[index],
                            sap.ui.model.FilterOperator.EQ,
                            sValue
                        ));
                    }
                });
                
                // Add filters for Input fields
                var inputFields = ["invoice_number", "rental_company_name", "leasing_company_name"];
                aInputs.forEach(function(oInput, index) {
                    var sValue = oInput.getValue().trim();
                    if (sValue) {
                        aFilters.push(new sap.ui.model.Filter(
                            inputFields[index],
                            sap.ui.model.FilterOperator.Contains,
                            sValue
                        ));
                    }
                });
                
                var oBinding = oTableInvoiceComparison.getBinding("items");
                if (oBinding) {
                    if (aFilters.length > 0) {
                        var oCombinedFilter = new sap.ui.model.Filter({
                            filters: aFilters,
                            and: true
                        });
                        oBinding.filter(oCombinedFilter);
                    } else {
                        oBinding.filter([]);
                    }
                }
                
                oFilterWsInvoiceDialog.close();
            }
        })
    ],
    afterClose: function() {
        // Optional: Add any cleanup needed after dialog closes
    }
}).addStyleClass("sapUiSizeCompact");


// Create scorecard tiles with empty/zero initial values
var oScoreCards = new sap.m.HBox({
    justifyContent: "SpaceBetween",
    width: "100%",
    wrap: "Wrap",
    items: [
        new sap.m.VBox({
            width: "13%",
            items: [
                new sap.m.Label({ text: "Total Work Orders", design: "Bold" }),
                new sap.m.Text({ text: "0"}).addStyleClass("scoreCardValue")
            ]
        }).addStyleClass("scoreCard"),
        new sap.m.VBox({
            width: "15%",
            items: [
                new sap.m.Label({ text: "Total Approved Amount", design: "Bold" }),
                new sap.m.Text({ text: "Rp 0" }).addStyleClass("scoreCardValue")
            ]
        }).addStyleClass("scoreCard"),
        new sap.m.VBox({
            width: "15%",
            items: [
                new sap.m.Label({ text: "Total Invoiced Amount", design: "Bold" }),
                new sap.m.Text({ text: "Rp 0" }).addStyleClass("scoreCardValue")
            ]
        }).addStyleClass("scoreCard"),
        new sap.m.VBox({
            width: "15%",
            items: [
                new sap.m.Label({ text: "Discrepancies Total", design: "Bold" }),
                new sap.m.Text({ text: "0"}).addStyleClass("scoreCardValue")
            ]
        }).addStyleClass("scoreCard"),
        new sap.m.VBox({
            width: "13%",
            items: [
                new sap.m.Label({ text: "No of Discrepancies", design: "Bold" }),
                new sap.m.Text({ text: "0" }).addStyleClass("scoreCardValue")
            ]
        }).addStyleClass("scoreCard"),
        new sap.m.VBox({
            width: "13%",
            items: [
                new sap.m.Label({ text: "(+ve) Total", design: "Bold" }),
                new sap.m.Text({ text: "Rp 0"}).addStyleClass("scoreCardValue positiveValue")
            ]
        }).addStyleClass("scoreCard"),
        new sap.m.VBox({
            width: "13%",
            items: [
                new sap.m.Label({ text: "(-ve) Total", design: "Bold" }),
                new sap.m.Text({ text: "Rp 0" }).addStyleClass("scoreCardValue negativeValue")
            ]
        }).addStyleClass("scoreCard")
    ]
}).addStyleClass("scoreCardContainer");

// Update the CSS for better layout
var scoreCardStyle = document.createElement('style');
scoreCardStyle.innerHTML = `
    .scoreCardContainer {
        padding: 1rem;
        background: #f5f6f7;
        margin-bottom: 1rem;
        display: flex;
        justify-content: space-between;
        align-items: stretch;
    }
    .scoreCard {
        background: white;
        padding: 1rem;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        margin: 0.5rem;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    .scoreCardValue {
        font-size: 24px;
        font-weight: bold;
        color: #354a5f;
        margin-top: 0.5rem;
        text-align: center;
    }
    .positiveValue {
        color: #28a745;
    }
    .negativeValue {
        color: #dc3545;
    }
    .sapMLabel {
        text-align: center;
        width: 100%;
    }
`;
document.head.appendChild(scoreCardStyle);

// Function to update scorecard values
function updateScoreCards(results) {
    var totalWorkOrders = results.length;
    var totalApproved = 0;
    var totalInvoiced = 0;
    var discrepanciesCount = 0;
    var discrepanciesTotal = 0;
    var positiveTotal = 0;
    var negativeTotal = 0;

    results.forEach(function(item) {
        var approved = parseFloat(item.workshop_cost) || 0;
        var invoiced = parseFloat(item.invoice_amount) || 0;
        var difference = invoiced - approved;
        
        totalApproved += approved;
        totalInvoiced += invoiced;
        
        if (approved !== invoiced) {
            discrepanciesCount++;
            discrepanciesTotal += Math.abs(difference);
            
            // Calculate positive and negative totals
            if (difference > 0) {
                positiveTotal += difference;
            } else if (difference < 0) {
                negativeTotal += difference;
            }
        }
    });

    // Update scorecard values
    oScoreCards.getItems()[0].getItems()[1].setText(totalWorkOrders);
    oScoreCards.getItems()[1].getItems()[1].setText("Rp " + totalApproved.toLocaleString());
    oScoreCards.getItems()[2].getItems()[1].setText("Rp " + totalInvoiced.toLocaleString());
    oScoreCards.getItems()[3].getItems()[1].setText(discrepanciesTotal.toLocaleString());
    oScoreCards.getItems()[4].getItems()[1].setText(discrepanciesCount);
    oScoreCards.getItems()[5].getItems()[1].setText("Rp " + positiveTotal.toLocaleString());
    oScoreCards.getItems()[6].getItems()[1].setText("Rp " + Math.abs(negativeTotal).toLocaleString());
}

// Update the function to get unique workshop names instead of groups
function getUniqueWorkshopNames(results) {
    var workshopNames = new Set();
    results.forEach(function(item) {
        if (item.workshop_name) {
            workshopNames.add(item.workshop_name);
        }
    });
    var uniqueNames = Array.from(workshopNames);
    uniqueNames.sort(); // Sort alphabetically
    return uniqueNames;
}

// Update the fetchInvoiceComparision function
function fetchInvoiceComparision() {
    oTableInvoiceComparison.setBusy(true);
    
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getAllInvoiceCompClosedWOAPI("Closed",oTableInvoiceComparison);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getAllInvoiceCompClosedWOByWorkshopAPI("Closed",oTableInvoiceComparison);
    }else{
        getAllInvoiceCompClosedWOByWorkshopGroupAPI("Closed",oTableInvoiceComparison);
    }
    // Car_Workorder.where({master_email:emailUser,wo_status:"Closed"}).take(2000).orderByDescending("createdAt").read().done(function (results) {
    //     // Filter out rows where Workshop Group is NULL and wo_status is GRN
    //     var filteredResults = results.filter(function(item) {
    //         return (item.ws_group_name !== null &&
    //                item.ws_group_name !== undefined &&
    //                item.ws_group_name !== "") &&
    //                (item.wo_status !== "GRN") &&
    //               !nullCheckAll(item.grn_number) &&
    //                 nullCheckAll(item.invoice_number);
    //     });
        
    //     // Store all workorder numbers
    //     var allWorkorderNumbers = filteredResults.map(function(item) {
    //         return item.wo_number;
    //     });

    //     // Log to console
    //     // console.log("=== Invoice Comparison Workorders ===");
    //     // console.log("Total Workorders:", allWorkorderNumbers.length);
    //     // console.log("Workorder Numbers:", allWorkorderNumbers);
        
    //     var oModel = new sap.ui.model.json.JSONModel();
    //     oModel.setData({ modelData: filteredResults });
    //     oTableInvoiceComparison.setModel(oModel);
    //     oTableInvoiceComparison.bindItems({ path: "/modelData", template : invoiceComparisonTemplate });
        
    //     // Get toolbar content
    //     var oToolbar = oTableInvoiceComparison.getHeaderToolbar();
        
    //     // Find the Workshop Name ComboBox
    //     var oComboBox = null;
    //     oToolbar.getContent().forEach(function(control) {
    //         if (control instanceof sap.m.ComboBox) {
    //             oComboBox = control;
    //         }
    //     });
        
    //     if (oComboBox) {
    //         // Clear existing items and add "All Workshop Names"
    //         oComboBox.removeAllItems();
    //         oComboBox.addItem(new sap.ui.core.Item({ key: "all", text: "All Workshop Names" }));
            
    //         // Get unique workshop names
    //         var uniqueNames = new Set();
    //         filteredResults.forEach(function(item) {
    //             if (item.workshop_name) {
    //                 uniqueNames.add(item.workshop_name);
    //             }
    //         });
            
    //         // Add workshop names to ComboBox
    //         Array.from(uniqueNames).sort().forEach(function(name) {
    //             oComboBox.addItem(new sap.ui.core.Item({ 
    //                 key: name, 
    //                 text: name 
    //             }));
    //         });
    //     }
        
    //     updateScoreCards(filteredResults);
    //     oTableInvoiceComparison.setBusy(false);
    // });
}

// First, let's create variables to store workshop names, their emails and master email
var workshopEmailMap = new Map();
var masterEmail = "";

// Update to store master_email
function getemailsforworkshop(){
        workshopData = workshop4WJSONData;
        
        // Store and print master_email
        if(workshopData && workshopData.length > 0) {
            masterEmail = workshopData[0].master_email;
        }

        // Populate the workshop-email map
        workshopData.forEach(function(workshop) {
            if (workshop.workshop_name && workshop.email) {
                workshopEmailMap.set(workshop.workshop_name, workshop.email);
            }
        });
        

        var oToolbar = oTableInvoiceComparison.getHeaderToolbar();
                
        // Find the Workshop Name ComboBox
        var oComboBox = null;
        oToolbar.getContent().forEach(function(control) {
            if (control instanceof sap.m.ComboBox) {
                oComboBox = control;
            }
        });
        
        
        if (oComboBox) {
            oComboBox.removeAllItems();
            var filteredWorkshopForInvoice = [...workshop4WJSONData];
        
            if(oxmaint_role == 'Workshop'){
                oComboBox.setVisible(false);
                getInvoiceCompareData(oxmaint_workshop_number,oTableInvoiceComparison)
                var oEmailButton = null;
                oToolbar.getContent().forEach(function(control) {
                    if (control instanceof sap.m.Button && control.hasStyleClass("emailButton")) {
                        oEmailButton = control;
                    }
                });

                if (oEmailButton) {
                    var email = workshopEmailMap.get(oxmaint_workshop_name);
                    if (email) {
                        oEmailButton.setText(email);
                        oEmailButton.setVisible(true);
                    } else {
                        oEmailButton.setVisible(false);
                    }
                }
                // filteredWorkshopForInvoice = filteredWorkshopForInvoice.filter(a=> a.workshop_number == oxmaint_workshop_number);
            }else if(oxmaint_role == 'Workshop Group Admin'){
                filteredWorkshopForInvoice = filteredWorkshopForInvoice.filter(a=> a.ws_group_number == oxmaint_ws_group_number);
            };


            // Add workshop names to ComboBox
            filteredWorkshopForInvoice.sort(function(a, b) {
                return a.workshop_name.localeCompare(b.workshop_name);
            }).forEach(function(name) {
                oComboBox.addItem(new sap.ui.core.Item({ 
                    key: name.workshop_number, 
                    text: name.workshop_name 
                }));
            });
            
        }


}

// Function to export selected table data to Excel
function exportTableToExcel() {
    var aItems = oTableInvoiceComparison.getItems();
    var exportData = [];
    
    // Get only checked rows
    aItems.forEach(function(oItem) {
        if (oItem.getCells()[0].getSelected()) {
            var modelData = oItem.getBindingContext().getObject();
            var difference = parseFloat(modelData.invoice_amount || 0) - parseFloat(modelData.workshop_cost || 0);
            var status = parseFloat(modelData.workshop_cost) === parseFloat(modelData.invoice_amount) ? "Matched" : "Discrepancy";
            
            exportData.push({
                "Workshop Group Number": modelData.ws_group_number || "",
                "Workshop Group Name": modelData.ws_group_name || "",
                "Workshop Number": modelData.workshop_number || "",
                "Workshop Name": modelData.workshop_name || "",
                "Workorder No": modelData.wo_number || "",
                "License Plate": modelData.license_number || "",
                "Approved Amount": modelData.workshop_cost || "",
                "Invoice Amount": modelData.invoice_amount || "",
                "Invoice Number": modelData.invoice_number || "",
                "Rental Company": modelData.rental_company_name || "",
                "Leasing Company": modelData.leasing_company_name || "",
                "Difference": difference.toFixed(2),
                "Status": status,
                "Date": modelData.created_date || ""
            });
        }
    });

    // Check if any rows are selected
    if (exportData.length === 0) {
        sap.m.MessageBox.error("Please select at least one row to export");
        return;
    }

    // Create worksheet
    var ws = XLSX.utils.json_to_sheet(exportData);
    
    // Create workbook
        var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Invoice Comparison");
    
    // Save file
    XLSX.writeFile(wb, "Invoice_Comparison_Report.xlsx");
}

// Call the function to load data
// loadAndDisplayData();


var invoiceCompare = new sap.m.VBox({
            items: [
        oScoreCards,
                oTableInvoiceComparison
    ]
});



// Define the Invoice Comparison page
// var oAppInvoiceComparisonPage = new sap.m.Page("invoice_comparison_page", {
//     title: oBundle.getText("Invoice Comparison Dashboard"),
//     content: [
//         new sap.m.VBox({
//             items: [
//                 oScoreCards,
//                 oTableInvoiceComparison
//             ]
//         })
//     ]
// });

// Add custom CSS for the title
var titleStyle = document.createElement('style');
titleStyle.innerHTML = `
    #invoice_comparison_page-title {
        font-size: 28px !important;
        font-weight: bold;
    }
`;
document.head.appendChild(titleStyle);

// Update the email style for button
var emailStyle = document.createElement('style');
emailStyle.innerHTML = `
    .emailButton {
        background-color: #f5f6f7 !important;
        border: 1px solid #d3d7d9 !important;
        border-radius: 4px !important;
        color: #0854a0 !important;
        font-style: italic !important;
        margin-left: 8px !important;
        cursor: default !important;
        min-width: 200px !important;
        text-align: left !important;
    }
    .emailButton:hover {
        background-color: #f5f6f7 !important;
    }
`;
document.head.appendChild(emailStyle);


// Add custom styling for the filter dialog
var filterDialogStyle = document.createElement('style');
filterDialogStyle.innerHTML = `
    .sapMDialog .sapMVBox .sapMLabel {
        margin-top: 1rem;
        margin-bottom: 0.5rem;
    }
    .sapMDialog .sapMVBox .sapMInput {
        margin-bottom: 0.5rem;
    }
    .filterCheckboxContainer {
        margin-top: 0.5rem;
        margin-bottom: 1rem;
    }
    .filterCheckbox {
        margin-right: 2rem;
    }
    .filterCheckbox .sapMCb {
        display: flex;
        align-items: center;
    }
    .filterCheckbox .sapMCbLabel {
        position: relative;
        top: -5px;
        line-height: 1;
    }
`;
document.head.appendChild(filterDialogStyle);

// Function to populate filter dialog dropdowns
function populateWsInvoiceFilterDropdowns() {
    var oBinding = oTableInvoiceComparison.getBinding("items");
    if (!oBinding) return;

    var aData = oBinding.getModel().getData().modelData;

    
    // Get unique values only for ComboBox fields
    var uniqueValues = {
        workshopGroups: new Set(),
        licenseNumbers: new Set()
    };

    aData.forEach(function(item) {
        if (item.ws_group_name) uniqueValues.workshopGroups.add(item.ws_group_name);
        if (item.license_number) uniqueValues.licenseNumbers.add(item.license_number);
    });

    // Get ComboBoxes from dialog (only first two now)
    var aComboBoxes = oFilterWsInvoiceDialog.getContent()[0].getItems().filter(function(item) {
        return item instanceof sap.m.ComboBox;
    });

    // Populate Workshop Group ComboBox
    aComboBoxes[0].removeAllItems();
    aComboBoxes[0].addItem(new sap.ui.core.Item({ key: "", text: "All Workshop Groups" }));
    Array.from(uniqueValues.workshopGroups).sort().forEach(function(group) {
        aComboBoxes[0].addItem(new sap.ui.core.Item({ key: group, text: group }));
    });

    // Populate License Number ComboBox
    aComboBoxes[1].removeAllItems();
    aComboBoxes[1].addItem(new sap.ui.core.Item({ key: "", text: "All License Numbers" }));
    Array.from(uniqueValues.licenseNumbers).sort().forEach(function(license) {
        aComboBoxes[1].addItem(new sap.ui.core.Item({ key: license, text: license }));
    });
}

// Update the Clear Filter functionality
function clearWsInvoiceFilters() {
    var aComboBoxes = oFilterWsInvoiceDialog.getContent()[0].getItems().filter(function(item) {
        return item instanceof sap.m.ComboBox;
    });
    var aInputs = oFilterWsInvoiceDialog.getContent()[0].getItems().filter(function(item) {
        return item instanceof sap.m.Input;
    });
    
    // Clear ComboBoxes
    aComboBoxes.forEach(function(oComboBox) {
        oComboBox.setSelectedKey("");
    });
    
    // Clear Inputs
    aInputs.forEach(function(oInput) {
        oInput.setValue("");
    });
    
    // Clear Checkboxes in dialog
    var oCheckBoxes = oFilterWsInvoiceDialog.getContent()[0].getItems().slice(-1)[0].getItems();
    oCheckBoxes[0].setSelected(false);
    oCheckBoxes[1].setSelected(false);
    
    // Clear table filters
    var oBinding = oTableInvoiceComparison.getBinding("items");
    if (oBinding) {
        oBinding.filter([]);
    }

    // Uncheck all rows and header checkbox
    var oHeaderCheckBox = oTableInvoiceComparison.getColumns()[0].getHeader();
    oHeaderCheckBox.setSelected(false);
    
    var aItems = oTableInvoiceComparison.getItems();
    aItems.forEach(function(oItem) {
        oItem.getCells()[0].setSelected(false);
    });
}

function attachInvoiceDocument(workorderIds) {
    var fileUploader = new sap.ui.unified.FileUploader({
        name: "file",
        uploadUrl: `${jrs_go_api_url_name}/upload/bulk_upload_grn`,
        sendXHR: true,
        useMultipart: true,
        fileType: ["xlsx", "xls"],
        change: function(oEvent) {
            var file = oEvent.getParameter("files")[0];
            if (!file) {
                return;
            }

            var reader = new FileReader();
            reader.onload = function(e) {
                try {
                    var workbook = XLSX.read(e.target.result, {
                        type: 'binary'
                    });

                    var firstSheet = workbook.SheetNames[0];
                    var worksheet = workbook.Sheets[firstSheet];
                    var excelData = XLSX.utils.sheet_to_json(worksheet);

                    const allowedExcelKeys = ['Workshop ID', 'GRN Number', 'GRN Date', 'Workorder Number', 'Note'];
                    const keys = Object.keys(excelData[0]);
                    console.log(keys)
                    // const isValidColumns = keys.every(key => allowedExcelKeys.includes(key)) && keys.length === allowedExcelKeys.length;

                    // if(!isValidColumns){
                    //     sap.m.MessageBox.error("Column Name are invalid");
                    //     return;
                    // }

                    const invalidKeys = keys.filter(key => !allowedExcelKeys.includes(key));

                    if (invalidKeys.length > 0 || keys.length !== allowedExcelKeys.length) {
                        const message = "Invalid Column(s): " + invalidKeys.join(", ");
                        sap.m.MessageBox.error(message);
                        return;
                    }

                    // Get workorder numbers from the table
                    var tableWorkorders = oTableInvoiceComparison.getModel()
                        .getData().modelData
                        .map(function(item) {
                            return item.wo_number;
                        });

                    // Get workorder numbers from Excel
                    var excelWorkorders = excelData.map(function(row) {
                        return row['Workorder Number'];
                    });

                    // // Validate workorders
                    var invalidWorkorders = excelWorkorders.filter(function(wo) {
                        return !tableWorkorders.includes(wo);
                    });
                    console.log(invalidWorkorders)
                    if (invalidWorkorders.length > 0) {
                        sap.m.MessageBox.error(
                            "The following workorder numbers were not found in the system:\n\n" + 
                            invalidWorkorders.join("\n")
                        );
                        return;
                    }

                    // Confirm before proceeding
                    sap.m.MessageBox.confirm(
                        "Do you want to upload the invoice document?",
                        {
                            onClose: function(oAction) {
                                if (oAction === sap.m.MessageBox.Action.OK) {
                                    // Show busy dialog
                                    var busyDialog = new sap.m.BusyDialog({
                                        title: "Processing",
                                        text: "Please wait..."
                                    });
                                    busyDialog.open();

                                    // Make API call
                                    var formData = new FormData();
                                    formData.append("file", file);
                                    formData.append("master_email", emailUser);

                                    $.ajax({
                                        url: `${jrs_go_api_url_name}/upload/bulk_upload_grn`,
                                        method: 'POST',
                                        data: formData,
                                        processData: false,
                                        contentType: false,
                                        headers: {
                                            'X-API-Key': jrs_go_api_key,
                                            'accept': 'application/json'
                                        },
                                        success: function(response) {
                                            busyDialog.close();
                                            sap.m.MessageToast.show("File uploaded successfully!");
                                            // fetchInvoiceComparision();
                                            refreshCurrentWorkshopInvoiceData();
                                            oDialog.close();
                                        },
                                        error: function(xhr, status, error) {
                                            busyDialog.close();
                                            console.error("Upload failed:", xhr.responseJSON.status);
                                            sap.m.MessageBox.error("Upload failed: " + xhr.responseJSON.status);
                                        }
                                    });
                                }
                            }
                        }
                    );

                } catch (error) {
                    console.error("Error processing file:", error);
                    sap.m.MessageBox.error("Error processing file. Please ensure you're uploading a valid Excel file.");
                }
            };
            
            reader.readAsBinaryString(file);
        }
    });

    var oDialog = new sap.m.Dialog({
        title: "Upload GRN Document",
        contentWidth: "50%",
        content: [
            new sap.m.VBox({
                items: [
                    new sap.m.Text({
                        text: "Select Excel file to upload"
                    }).addStyleClass("sapUiSmallMarginBottom"),
                    fileUploader
                ]
            }).addStyleClass("sapUiSmallMargin")
        ],
        buttons: [
            new sap.m.Button({
                text: "Cancel",
                press: function() {
                    oDialog.close();
                }
            })
        ],
        afterClose: function() {
            oDialog.destroy();
        }
    });

    oDialog.open();
}

// Add this function to handle API authentication
function authenticateAPI() {
    return new Promise((resolve, reject) => {
        // Make authentication request
        $.ajax({
            url: `${jrs_go_api_url_name}/auth`,  // Authentication endpoint
            method: 'POST',
            headers: {
                'X-API-Key': jrs_go_api_key,
                'accept': 'application/json'
            },
            success: function(response) {
                console.log("API Authentication successful");
                resolve(true);
            },
            error: function(xhr, status, error) {
                console.error("API Authentication failed:", error);
                reject(error);
            }
        });
    });
};



function reopenInvoiceDialog(){
    // Step 3: Create the search field
    var oSearch = new sap.m.SearchField({
      placeholder: "Enter invoice number to reopen",
  });

  // Step 4: Create the dialog
  var oDialog = new sap.m.Dialog({
    contentWidth: "30%",
      title: "Reopen Invoices",
      content: [oSearch],
      beginButton: new sap.m.Button({
          text: "Reopen",
          type: "Emphasized",
          press: function () {
            busyDialog.open();
            var searchInvoiceNumber =  oSearch.getValue();

            var alltableItemdata = oTableInvoiceComparison.getModel().getData();
            var tableItem = alltableItemdata['modelData'];

            var foundItem = tableItem.find(item => item.invoice_number === searchInvoiceNumber);
            if (foundItem) {
                Car_Invoice.where({master_email:emailUser,invoice_number:searchInvoiceNumber}).take(10)
                .orderByDescending("createdAt").read().done(function (results) {
                    if(results.length == 1){
                        // console.log(results[0]['id'])
                        resetInvoiceAPI(results[0]['id'], results[0]['invoice_number'],oDialog,results[0]['wo_number']);
                    }else if(results.length > 1){
                        busyDialog.close();
                        sap.m.MessageBox.error(oBundle.getText("Multiple Invoice number found!"));
                    }else{
                        busyDialog.close();
                        sap.m.MessageBox.error(oBundle.getText("Invoice number not found!"));
                    }
                });
            } else {
                busyDialog.close();
                sap.m.MessageBox.error(oBundle.getText("Invoice number not found!"));
            }


          }
      }),
      endButton: new sap.m.Button({
          text: "Close",
          type:sap.m.ButtonType.Reject,
          press: function () {
              oDialog.close();
          }
      }),
      afterClose: function () {
          oDialog.destroy(); // Clean up
      }
  }).open();

  // Step 5: Create the button to open the dialog
 
};



function refreshCurrentWorkshopInvoiceData(){
    var oToolbar = oTableInvoiceComparison.getHeaderToolbar();
                
    var oComboBox = null;
    oToolbar.getContent().forEach(function(control) {
        if (control instanceof sap.m.ComboBox) {
            oComboBox = control;
        }
    });
                
    if (oComboBox) {
        let selectedWorkshopNumber = oComboBox.getSelectedKey();
        if(nullCheckAll(selectedWorkshopNumber)){
            getInvoiceCompareData(selectedWorkshopNumber,oTableInvoiceComparison);
        }else if(oxmaint_role == 'Workshop'){
            getInvoiceCompareData(oxmaint_workshop_number,oTableInvoiceComparison);
        }
    }
}

