// Table definition should be at the top
// var Car_Workorder = client.getTable('car_workorder');
// var Car_Workshop = client.getTable('car_workshop');

// Create the main page container
var oAppSupplierInvoiceComparisonPage = new sap.m.Page({
    title: "Supplier Invoice Dashboard",
    showHeader: true,
    floatingFooter: false
});

// Create the table for supplier invoice
var oTableSupplierInvoice = new sap.m.Table({
    growing: true,
    noDataText: oBundle.getText("No_Data"),
    growingTriggerText: oBundle.getText("More"),
    sticky: [sap.m.Sticky.ColumnHeaders, sap.m.Sticky.HeaderToolbar],
    growingThreshold: 25,
    growingScrollToLoad: false,
    
    columns: [
        new sap.m.Column({
            width: "5%",
            header: new sap.m.CheckBox({
                select: function(oEvent) {
                    var bSelected = oEvent.getParameter("selected");
                    var aItems = oTableSupplierInvoice.getItems();
                    aItems.forEach(function(oItem) {
                        oItem.getCells()[0].setSelected(bSelected);
                    });
                }
            })
        }),
        new sap.m.Column({ 
            header: new sap.m.Text({ 
                text: "Workshop Group",
                wrapping: true
            }).addStyleClass("sapMColumnHeaderBold"),
            width: "10%",
            minScreenWidth: "Small",
            demandPopin: true,
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Text({ 
                text: "Workshop Name",
                wrapping: true
            }).addStyleClass("sapMColumnHeaderBold"),
            width: "10%",
            minScreenWidth: "Small",
            demandPopin: true,
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Text({ 
                text: "Workorder No",
                wrapping: true
            }).addStyleClass("sapMColumnHeaderBold"),
            width: "10%",
            minScreenWidth: "Small",
            demandPopin: true,
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        new sap.m.Column({ 
            header: new sap.m.Text({ 
                text: "License Plate",
                wrapping: true
            }).addStyleClass("sapMColumnHeaderBold"),
            width: "8%",
            minScreenWidth: "Small",
            demandPopin: true,
            popinDisplay: "Block",
            hAlign: "Begin"
        }),
        // new sap.m.Column({ 
        //     header: new sap.m.Text({ 
        //         text: "Labor Cost",
        //         wrapping: true
        //     }).addStyleClass("sapMColumnHeaderBold"),
        //     width: "8%",
        //     minScreenWidth: "Tablet",
        //     demandPopin: true,
        //     popinDisplay: "Inline",
        //     hAlign: "End"
        // }),
        // new sap.m.Column({ 
        //     header: new sap.m.Text({ 
        //         text: "Parts Cost",
        //         wrapping: true
        //     }).addStyleClass("sapMColumnHeaderBold"),
        //     width: "8%",
        //     minScreenWidth: "Tablet",
        //     demandPopin: true,
        //     popinDisplay: "Inline",
        //     hAlign: "End"
        // }),
        // new sap.m.Column({ 
        //     header: new sap.m.Text({ 
        //         text: "Total Parts",
        //         wrapping: true
        //     }).addStyleClass("sapMColumnHeaderBold"),
        //     width: "8%",
        //     minScreenWidth: "Tablet",
        //     demandPopin: true,
        //     popinDisplay: "Inline",
        //     hAlign: "End"
        // }),
        new sap.m.Column({ 
            header: new sap.m.Text({ 
                text: "Total Cost",
                wrapping: true
            }).addStyleClass("sapMColumnHeaderBold"),
            width: "8%",
            minScreenWidth: "Tablet",
            demandPopin: true,
            popinDisplay: "Inline",
            hAlign: "End"
        }),
        new sap.m.Column({ 
            header: new sap.m.Text({ 
                text: "Invoice Number",
                wrapping: true
            }).addStyleClass("sapMColumnHeaderBold"),
            width: "12%",
            minScreenWidth: "Tablet",
            demandPopin: true,
            popinDisplay: "Inline",
            hAlign: "Begin"
        }),
        // new sap.m.Column({ 
        //     header: new sap.m.Text({ 
        //         text: "Rental Company",
        //         wrapping: true
        //     }).addStyleClass("sapMColumnHeaderBold"),
        //     width: "12%",
        //     minScreenWidth: "Desktop",
        //     demandPopin: true,
        //     popinDisplay: "Inline",
        //     hAlign: "Begin"
        // }),
        // new sap.m.Column({ 
        //     header: new sap.m.Text({ 
        //         text: "Leasing Company",
        //         wrapping: true
        //     }).addStyleClass("sapMColumnHeaderBold"),
        //     width: "12%",
        //     minScreenWidth: "Desktop",
        //     demandPopin: true,
        //     popinDisplay: "Inline",
        //     hAlign: "Begin"
        // }),
        new sap.m.Column({ 
            header: new sap.m.Text({ 
                text: "Date",
                wrapping: true
            }).addStyleClass("sapMColumnHeaderBold"),
            width: "10%",
            minScreenWidth: "Desktop",
            demandPopin: true,
            popinDisplay: "Inline",
            hAlign: "Begin"
        })
    ],
    headerToolbar: new sap.m.Toolbar({
        content: [
            new sap.m.Button({
                text: "Export to Excel",
                icon: "sap-icon://excel-attachment",
                type: "Emphasized",
                press: function() {
                    exportSelectedToExcel();
                }
            }),
            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_Supplier_Invoice.xlsx", "_blank");
                            }
                        }),
                        new sap.m.MenuItem({
                            text: "Upload Excel",
                            press: function() {
                                attachSupplierInvoiceDocument();
                            }
                        })
                    ]
                })
            }),
            new sap.m.ToolbarSpacer(),
            new sap.m.ComboBox({
                width: "200px",
                placeholder: "Select Workshop Name",
                selectionChange: function(oEvent) {
                    var selectedWorkshop = oEvent.getParameter("selectedItem").getKey();
                    var oBinding = oTableSupplierInvoice.getBinding("items");
                    var emailButton = this.getParent().getContent()
                        .find(control => control instanceof sap.m.Button && control.getTooltip() === "Workshop Email");
                    
                    if (selectedWorkshop) {
                        // Get email for selected workshop
                        Car_Workshop.where({
                            master_email: emailUser,
                            workshop_name: selectedWorkshop
                        }).read().done(function(results) {
                            if (results && results.length > 0 && results[0].email) {
                                emailButton.setText(results[0].email);
                                emailButton.setVisible(true);
                            } else {
                                emailButton.setVisible(false);
                            }
                        });

                        var oFilter = new sap.ui.model.Filter(
                            "workshop_name",
                            sap.ui.model.FilterOperator.EQ,
                            selectedWorkshop
                        );
                        oBinding.filter([oFilter]);
                    } else {
                        emailButton.setVisible(false);
                        oBinding.filter([]);
                    }
                }
            }),
            new sap.m.Button({
                text: "", // Email will be set here
                type: "Transparent",
                tooltip: "Workshop Email",
                visible: false,
                enabled: true, // Make it clickable
                press: function() {
                    var selectedItems = oTableSupplierInvoice.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 laborCost = parseFloat(data.labor_item_cost) || 0;
                                        var partsCost = parseFloat(data.parts_cost) || 0;
                                        var totalCost = parseFloat(data.total_cost) || 0;
                                        
                                        return {
                                            workshop_group: data.ws_group_name,
                                            workshop_name: data.workshop_name,
                                            workorder_no: data.wo_number,
                                            license_plate: data.license_number,
                                            approved_amount: totalCost.toString(),
                                            invoice_amount: (laborCost + partsCost).toString(),
                                            invoice_number: data.supplier_invoice_number,
                                            rental_company: data.rental_company_name || "-",
                                            leasing_company: data.leasing_company_name || "-",
                                            difference: (totalCost - (laborCost + partsCost)).toFixed(2),
                                            status: totalCost === (laborCost + partsCost) ? "Matched" : "Discrepancy"
                                        };
                                    });

                                    // Call the 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("Upload failed:", xhr.responseJSON.status);
                                            sap.m.MessageBox.error("Upload failed: " + xhr.responseJSON.status);
                                        }
                                    });
                                }
                            }.bind(this)
                        }
                    );
                }
            }).addStyleClass("emailButton"),
            new sap.m.SearchField({
                width: "250px",
                placeholder: "Search Workorder, License Plate, Part Name...",
                liveChange: function(oEvent) {
                    var sQuery = oEvent.getParameter("newValue");
                    var oBinding = oTableSupplierInvoice.getBinding("items");
                    
                    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("supplier_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)
                        ];
                        
                        var oFilter = new sap.ui.model.Filter({
                            filters: aFilters,
                            and: false // This makes it an OR condition
                        });
                        
                        oBinding.filter(oFilter);
                    } else {
                        oBinding.filter([]);
                    }
                }
            }),
            new sap.m.Button({
                icon: "sap-icon://filter",
                type: "Transparent",
                press: function() {
                    clearFilters();
                    populateSuppFilterDropdowns();
                    oSupplierFilterDialog.open();
                }
            })
        ]
    })
}).addStyleClass("sapUiSizeCompact");

// First, create the score card layout with all tiles
var oSupplierScoreCardLayout = new sap.ui.layout.Grid({
    defaultSpan: "XL4 L4 M6 S12",
    vSpacing: 1,
    hSpacing: 1,
    content: [
        // First tile - Total Workorder Nos
        new sap.m.GenericTile({
            id: "workorderTile",
            header: "Total Workorder Nos",
            frameType: "OneByOne",
            tileContent: [
                new sap.m.TileContent({
                    content: new sap.m.NumericContent({
                        value: "0",
                        valueColor: "Neutral",
                        scale: "",
                        truncateValueTo: 20,
                        formatterValue: false,
                        withMargin: false
                    })
                })
            ]
        }).addStyleClass("tightGenericTile"),

        // Second tile - Total License Plates
        new sap.m.GenericTile({
            id: "licensePlateTile",
            header: "Total License Plates",
            frameType: "OneByOne",
            tileContent: [
                new sap.m.TileContent({
                    content: new sap.m.NumericContent({
                        value: "0",
                        valueColor: "Neutral",
                        scale: "",
                        truncateValueTo: 20,
                        formatterValue: false,
                        withMargin: false
                    })
                })
            ]
        }).addStyleClass("tightGenericTile"),

        // Third tile - Total Number of Parts
        new sap.m.GenericTile({
            id: "partsTile",
            header: "Total Cost",
            frameType: "OneByOne",
            tileContent: [
                new sap.m.TileContent({
                    content: new sap.m.NumericContent({
                        value: "0",
                        valueColor: "Neutral",
                        scale: "",
                        truncateValueTo: 20,
                        formatterValue: false,
                        withMargin: false
                    })
                })
            ]
        }).addStyleClass("tightGenericTile"),

        // Fourth tile - Total Labour Cost
        // new sap.m.GenericTile({
        //     header: "Total Labour Cost",
        //     frameType: "OneByOne",
        //     tileContent: [
        //         new sap.m.TileContent({
        //             content: new sap.m.NumericContent({
        //                 value: "Rp 0",
        //                 valueColor: "Neutral",
        //                 scale: "",
        //                 truncateValueTo: 20,
        //                 formatterValue: false,
        //                 withMargin: false
        //             })
        //         })
        //     ]
        // }).addStyleClass("tightGenericTile"),

        // // Fifth tile - Total Parts Cost
        // new sap.m.GenericTile({
        //     header: "Total Parts Cost",
        //     frameType: "OneByOne",
        //     tileContent: [
        //         new sap.m.TileContent({
        //             content: new sap.m.NumericContent({
        //                 value: "Rp 0",
        //                 valueColor: "Neutral",
        //                 scale: "",
        //                 truncateValueTo: 20,
        //                 formatterValue: false,
        //                 withMargin: false
        //             })
        //         })
        //     ]
        // }).addStyleClass("tightGenericTile"),

        // // Sixth tile - Overall Cost
        // new sap.m.GenericTile({
        //     header: "Overall Cost",
        //     frameType: "OneByOne",
        //     tileContent: [
        //         new sap.m.TileContent({
        //             content: new sap.m.NumericContent({
        //                 value: "Rp 0",
        //                 valueColor: "Neutral",
        //                 scale: "",
        //                 truncateValueTo: 20,
        //                 formatterValue: false,
        //                 withMargin: false
        //             })
        //         })
        //     ]
        // }).addStyleClass("tightGenericTile")
    ]
}).addStyleClass("supplierScoreCardGrid");

// Function to get unique values from data
function getUniqueValues(data, field) {
    var uniqueValues = new Set();
    data.forEach(function(item) {
        if (item[field]) {
            uniqueValues.add(item[field]);
        }
    });
    return Array.from(uniqueValues).sort();
}

// Create the filter dialog with Input fields instead of ComboBoxes
var oSupplierFilterDialog = 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"
                // })
            ]
        }).addStyleClass("sapUiSmallMargin")
    ],
    buttons: [
        new sap.m.Button({
            icon: "sap-icon://clear-filter",
            text: "Clear Filter",
            press: function() {
                clearFilters();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://decline",
            text: "Cancel",
            press: function() {
                oSupplierFilterDialog.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 = oSupplierFilterDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.ComboBox;
                });
                
                // Get Input fields (last three fields)
                var aInputs = oSupplierFilterDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.Input;
                });
                
                // 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 = ["supplier_invoice_number"];
                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 = oTableSupplierInvoice.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([]);
                    }
                }
                
                oSupplierFilterDialog.close();
            }
        })
    ]
}).addStyleClass("sapUiSizeCompact");

// Add this at the top of the file
var isFirstScoreCardUpdate = true;

function updateSupplierScoreCards(results) {
    // Check if this is a call from grab_invoice_comparison.js
    const callStack = new Error().stack;
    if (callStack.includes('grab_invoice_comparison.js')) {
        return;
    }

    try {
        // Calculate unique workorders
        var uniqueWorkorders = [...new Set(results.map(item => item.wo_number))];

        // Calculate unique license plates
        var uniqueLicensePlates = [...new Set(results.map(item => item.license_number))];

        // Calculate unique parts
        var uniqueParts = [...new Set(results.map(item => item.part_name))];

        // Calculate costs with proper number handling
        var totalLabourCost = results.reduce((sum, item) => {
            let cost = parseFloat(item.labor_item_cost) || 0;
            return sum + cost;
        }, 0);

        var totalPartsCost = results.reduce((sum, item) => {
            let cost = parseFloat(item.parts_cost) || 0;
            return sum + cost;
        }, 0);

        var overallCost = results.reduce((sum, item) => {
            let cost = parseFloat(item.supplier_cost) || 0;
            return sum + cost;
        }, 0);

        // Format numbers for display without rounding or truncating
        var formatCurrency = function(value) {
            let numStr = value.toString().replace(/[^\d.-]/g, '');
            let num = parseFloat(numStr);
            return new Intl.NumberFormat('id-ID', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 2
            }).format(num);
        };

        // Update the score cards
        var tiles = oSupplierScoreCardLayout.getContent();
        
        // Update count tiles (no currency formatting needed)
        tiles[0].getTileContent()[0].getContent()
            .setValue(uniqueWorkorders.length.toString())
            .setTruncateValueTo(20);

        tiles[1].getTileContent()[0].getContent()
            .setValue(uniqueLicensePlates.length.toString())
            .setTruncateValueTo(20);

        // tiles[2].getTileContent()[0].getContent()
        //     .setValue(uniqueParts.length.toString())
        //     .setTruncateValueTo(20);

        // Update cost tiles with full number display
        // tiles[3].getTileContent()[0].getContent()
        //     .setValue("Rp " + formatCurrency(totalLabourCost))
        //     .setTruncateValueTo(20)
        //     .setFormatterValue(false);

        // tiles[4].getTileContent()[0].getContent()
        //     .setValue("Rp " + formatCurrency(totalPartsCost))
        //     .setTruncateValueTo(20)
        //     .setFormatterValue(false);

        tiles[2].getTileContent()[0].getContent()
            .setValue("Rp " + formatCurrency(overallCost))
            .setTruncateValueTo(20)
            .setFormatterValue(false);

    } catch (error) {
        console.error("Error in updateSupplierScoreCards:", error);
    }
}

// Function to fetch and display supplier invoice data
function fetchSupplierInvoice() {
    if (!Car_Workorder) {
        console.error("Car_Workorder table not initialized");
        return;
    }

    oTableSupplierInvoice.setBusy(true);
    
    try {
        getSupplierInvoiceComparisionWO();
        // Car_Workorder.where({master_email: emailUser,supplier_wo_flag:"Supplier",supplier_inv_pick:"Done"})
        //     .take(2000)
        //     .orderByDescending("createdAt")
        //     .read()
        //     .done(function (results) {

        //         results = results.filter(function(item) {
        //             return !nullCheckAll(item.supplier_grn_number) && nullCheckAll(item.supplier_invoice_number);
        //         });
        //         // Store all workorder numbers
        //         var allSupplierWorkorders = results.map(function(item) {
        //             return item.wo_number;
        //         });

        //         // Log to console
        //         // console.log("=== Supplier Invoice Workorders ===");
        //         // console.log("Total Workorders:", allSupplierWorkorders.length);
        //         // console.log("Workorder Numbers:", allSupplierWorkorders);
                
        //         var oModel = new sap.ui.model.json.JSONModel();
        //         oModel.setData({ modelData: results });
        //         oTableSupplierInvoice.setModel(oModel);
                
        //         // Populate Workshop Name dropdown
        //         var uniqueWorkshops = [...new Set(results
        //             .map(item => item.workshop_name)
        //             .filter(item => item && item.trim() !== "")
        //         )].sort();

        //         var oWorkshopComboBox = oTableSupplierInvoice.getHeaderToolbar().getContent()
        //             .find(control => control instanceof sap.m.ComboBox);

        //         if (oWorkshopComboBox) {
        //             oWorkshopComboBox.removeAllItems();
        //             oWorkshopComboBox.addItem(new sap.ui.core.Item({
        //                 key: "",
        //                 text: "All Workshops"
        //             }));
        //             uniqueWorkshops.forEach(function(workshop) {
        //                 oWorkshopComboBox.addItem(new sap.ui.core.Item({
        //                     key: workshop,
        //                     text: workshop
        //                 }));
        //             });
        //         }

        //         // Update score cards with the results
        //         updateSupplierScoreCards(results);

        //         populateSuppFilterDropdowns();
                
        //         // Bind table items
        //         oTableSupplierInvoice.bindItems({
        //             path: "/modelData",
        //             template: new sap.m.ColumnListItem({
        //                 cells: [
        //                     new sap.m.CheckBox(),
        //                     new sap.m.Text({ text: "{ws_group_name}" }),
        //                     new sap.m.Text({ text: "{workshop_name}" }),
        //                     new sap.m.Text({ text: "{wo_number}" }),
        //                     new sap.m.Text({ text: "{license_number}" }),
        //                     // new sap.m.Text({ 
        //                     //     text: {
        //                     //         path: "labor_item_cost",
        //                     //         formatter: function(value) {
        //                     //             return value ? "Rp " + value : "Rp 0";
        //                     //         }
        //                     //     }
        //                     // }),
        //                     // new sap.m.Text({ 
        //                     //     text: {
        //                     //         path: "parts_cost",
        //                     //         formatter: function(value) {
        //                     //             return value ? "Rp " + value : "Rp 0";
        //                     //         }
        //                     //     }
        //                     // }),
        //                     // new sap.m.Text({ 
        //                     //     text: {
        //                     //         path: "total_parts_cost",
        //                     //         formatter: function(value) {
        //                     //             return value ? "Rp " + value : "Rp 0";
        //                     //         }
        //                     //     }
        //                     // }),
        //                     new sap.m.Text({ 
        //                         text: {
        //                             path: "supplier_cost",
        //                             formatter: function(value) {
        //                                 return value ? "Rp " + value : "Rp 0";
        //                             }
        //                         }
        //                     }),
        //                     new sap.m.Text({ text: "{supplier_invoice_number}" }),
        //                     // new sap.m.Text({ text: "{rental_company_name}" }),
        //                     // new sap.m.Text({ text: "{leasing_company_name}" }),
        //                     new sap.m.Text({ text: "{created_date}" })
        //                 ]
        //             })
        //         });
                
        //         oTableSupplierInvoice.setBusy(false);
        //     }, function(error) {
        //         console.error("Error fetching supplier invoice data:", error);
        //         oTableSupplierInvoice.setBusy(false);
        //         sap.m.MessageBox.error("Error fetching data. Please try again.");
        //     });
    } catch (e) {
        console.error("Error in fetchSupplierInvoice:", e);
        oTableSupplierInvoice.setBusy(false);
        sap.m.MessageBox.error("Error processing data. Please try again.");
    }
}

// Function to export selected rows to Excel
function exportSelectedToExcel() {
    var selectedItems = oTableSupplierInvoice.getItems().filter(function(item) {
        return item.getCells()[0].getSelected();
    });

    if (selectedItems.length === 0) {
        sap.m.MessageBox.warning("Please select at least one row to export.");
        return;
    }

    var aItems = oTableSupplierInvoice.getItems();
    var exportData = [];
    
    // Get only checked rows
    aItems.forEach(function(oItem) {
        if (oItem.getCells()[0].getSelected()) {
            var modelData = oItem.getBindingContext().getObject();
           
            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 || "",
                "Amount": modelData.supplier_cost || "",
                "Invoice Number": modelData.supplier_invoice_number || "",
            });
        }
    });


    // var data = selectedItems.map(function(item) {
    //     var cells = item.getCells();
    //     return {
    //         "Workorder No": cells[1].getText(),
    //         "License Plate": cells[2].getText(),
    //         "Labor Cost": cells[3].getText().replace("Rp ", ""),
    //         "Parts Cost": cells[4].getText().replace("Rp ", ""),
    //         "Total Parts Cost": cells[5].getText().replace("Rp ", ""),
    //         "Total Cost": cells[6].getText().replace("Rp ", "")
    //     };
    // });

    // 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, "Supplier Invoice");

    // Save file
    var fileName = "Supplier_Invoice_Export_" + new Date().toISOString().slice(0,10) + ".xlsx";
    XLSX.writeFile(wb, fileName);
}

// Add style for export button
var exportStyle = document.createElement('style');
exportStyle.type = 'text/css';
exportStyle.innerHTML = `
    .sapMBtn.exportButton {
        margin-right: 8px;
    }
`;
document.getElementsByTagName('head')[0].appendChild(exportStyle);

// Add style for the filter dialog
var filterStyle = document.createElement('style');
filterStyle.type = 'text/css';
filterStyle.innerHTML = `
    .sapMDialogSection {
        padding: 1rem;
    }
    .sapMLabel {
        margin-bottom: 0.5rem;
    }
    .sapMInput {
        margin-bottom: 1rem;
    }
`;
document.getElementsByTagName('head')[0].appendChild(filterStyle);

// Add custom CSS styles
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = `
    .tightGenericTile {
        height: 8rem !important;
        width: 100% !important;
    }
    .tightGenericTile .sapMGTHeader {
        padding-top: 0.1rem !important;
        margin-bottom: 0 !important;
        font-size: 1rem !important;
        height: 2.5rem !important;
    }
    .tightTileContent {
        padding-top: 0 !important;
        margin-top: -1rem !important;
    }
    .sapMGTContent {
        margin-top: -0.5rem !important;
        height: 4rem !important;
    }
    .sapMNCValue {
        margin-top: -0.5rem !important;
        font-size: 2rem !important;
    }
    .sapMTileCnt {
        margin-top: -0.5rem !important;
        padding-top: 0 !important;
        height: 4rem !important;
    }
    .supplierScoreCardGrid {
        padding: 1rem;
        margin: 0 !important;
    }
`;
document.getElementsByTagName('head')[0].appendChild(style);

// Add style for email button
var emailStyle = document.createElement('style');
emailStyle.type = 'text/css';
emailStyle.innerHTML = `
    .emailButton {
        margin-left: 8px !important;
        margin-right: 8px !important;
        color: #0854a0 !important;
    }
    .emailButton:hover {
        text-decoration: underline !important;
    }
`;
document.getElementsByTagName('head')[0].appendChild(emailStyle);

// Add the score cards and table to the page
// oAppSupplierInvoiceComparisonPage.addContent(oSupplierScoreCardLayout);
// oAppSupplierInvoiceComparisonPage.addContent(oTableSupplierInvoice);
var supplierInvoiceCompare = new sap.m.VBox({
    items: [
        oSupplierScoreCardLayout,
        oTableSupplierInvoice
    ]
});

// Initial data load - wrap in try-catch
// try {
//     fetchSupplierInvoice();
// } catch (e) {
//     console.error("Error initializing data:", e);
//     sap.m.MessageBox.error("Error initializing data. Please refresh the page.");
// }

// Add this function to populate filter dropdowns
function populateSuppFilterDropdowns() {
    try {
        var oModel = oTableSupplierInvoice.getModel();
        if (!oModel) return;
        
        var aData = oModel.getProperty("/modelData");
        if (!aData) return;

        // Get unique workshop groups
        var uniqueWorkshopGroups = [...new Set(aData
            .map(item => item.ws_group_name)
            .filter(item => item && item.trim() !== "")
        )].sort();

        // Get unique license plates
        var uniqueLicensePlates = [...new Set(aData
            .map(item => item.license_number)
            .filter(item => item && item.trim() !== "")
        )].sort();
       
        // Get unique Supplier invoice number
        // var uniqueSupplierInvoiceNumber = [...new Set(aData
        //     .map(item => item.supplier_invoice_number)
        //     .filter(item => item && item.trim() !== "")
        // )].sort();

        // Get the ComboBoxes
        var comboBoxes = oSupplierFilterDialog.getContent()[0].getItems()
            .filter(item => item instanceof sap.m.ComboBox);
        
        var oWorkshopGroupComboBox = comboBoxes[0];
        var oLicensePlateComboBox = comboBoxes[1];
        // var oInvoiceNumberComboBox = comboBoxes[2];

        // Clear existing items
        oWorkshopGroupComboBox.removeAllItems();
        oLicensePlateComboBox.removeAllItems();
        // oInvoiceNumberComboBox.removeAllItems();

        // Add items to Workshop Group ComboBox
        uniqueWorkshopGroups.forEach(function(group) {
            oWorkshopGroupComboBox.addItem(new sap.ui.core.Item({
                key: group,
                text: group
            }));
        });

        // Add items to License Plate ComboBox
        uniqueLicensePlates.forEach(function(plate) {
            oLicensePlateComboBox.addItem(new sap.ui.core.Item({
                key: plate,
                text: plate
            }));
        });
       
        // uniqueSupplierInvoiceNumber.forEach(function(invNumber) {
        //     oInvoiceNumberComboBox.addItem(new sap.ui.core.Item({
        //         key: invNumber,
        //         text: invNumber
        //     }));
        // });

    } catch (error) {
        console.error("Error populating filter dropdowns:", error);
    }
}

// Add this function to handle email retrieval
function getEmailsForWorkshop(workshopName) {
    Car_Workshop.where({
        master_email: emailUser,
        workshop_name: workshopName
    }).read().done(function(results) {
        if (results && results.length > 0) {
            var emails = results.map(function(item) {
                return item.email || '';
            }).filter(Boolean).join(', ');

            if (emails) {
                var dialog = new sap.m.Dialog({
                    title: "Workshop Emails",
                    contentWidth: "400px",
                    content: [
                        new sap.m.TextArea({
                            value: emails,
                            width: "100%",
                            rows: 4,
                            editable: false
                        })
                    ],
                    buttons: [
                        new sap.m.Button({
                            text: "Copy",
                            press: function() {
                                var textArea = dialog.getContent()[0];
                                textArea.selectText();
                                document.execCommand('copy');
                                sap.m.MessageToast.show("Emails copied to clipboard");
                            }
                        }),
                        new sap.m.Button({
                            text: "Close",
                            press: function() {
                                dialog.close();
                            }
                        })
                    ],
                    afterClose: function() {
                        dialog.destroy();
                    }
                });
                dialog.open();
            } else {
                sap.m.MessageBox.information("No emails found for this workshop");
            }
        } else {
            sap.m.MessageBox.information("No workshop details found");
        }
    }).fail(function(error) {
        console.error("Error fetching workshop emails:", error);
        sap.m.MessageBox.error("Error fetching workshop emails");
    });
}

// Add this function for handling supplier invoice uploads
function attachSupplierInvoiceDocument() {
    var fileUploader = new sap.ui.unified.FileUploader({
        name: "file",
        uploadUrl: `${jrs_go_api_url_name}/upload/supplier_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);

                    // Get workorder numbers from the table
                    var tableWorkorders = oTableSupplierInvoice.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);
                    });

                    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 supplier 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/supplier_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!");
                                            fetchSupplierInvoice();
                                            // get4WCompletedSuppInvoice();
                                            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 Supplier Invoice 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 clear filters
function clearFilters() {
    try {
        // Get all filter dialog inputs
        var filterContent = oSupplierFilterDialog.getContent()[0];
        
        // Clear ComboBoxes
        var comboBoxes = filterContent.getItems().filter(function(item) {
            return item instanceof sap.m.ComboBox;
        });
        comboBoxes.forEach(function(comboBox) {
            comboBox.setSelectedKey("");
        });

        // Clear Input fields
        var inputs = filterContent.getItems().filter(function(item) {
            return item instanceof sap.m.Input;
        });
        inputs.forEach(function(input) {
            input.setValue("");
        });

        // Clear the table binding filter
        var oBinding = oTableSupplierInvoice.getBinding("items");
        if (oBinding) {
            oBinding.filter([]);
        }

        // Clear the workshop filter in the toolbar
        var oWorkshopComboBox = oTableSupplierInvoice.getHeaderToolbar().getContent()
            .find(control => control instanceof sap.m.ComboBox);
        if (oWorkshopComboBox) {
            oWorkshopComboBox.setSelectedKey("");
        }

        // Clear the search field in the toolbar
        var oSearchField = oTableSupplierInvoice.getHeaderToolbar().getContent()
            .find(control => control instanceof sap.m.SearchField);
        if (oSearchField) {
            oSearchField.setValue("");
        }

        // Refresh the table
        fetchSupplierInvoice();

        sap.m.MessageToast.show("All filters have been cleared");
    } catch (error) {
        console.error("Error clearing filters:", error);
        sap.m.MessageBox.error("Error clearing filters. Please try again.");
    }
}
