// Vehicle Renewable Documents Page Layout
var oRenewablePageLayout = new sap.uxap.ObjectPageLayout("renewablePageLayout", {
    showTitleInHeaderContent: true,
    showHeaderContent: true,
    showFooter: false,
    sections: []
});

// Create the page
var vehicleRenewableDocPage = new sap.m.Page("renewablePage", {
    showHeader: false,
    content: [
        oRenewablePageLayout
    ]
});

// Variable to store the table data
var renewableDocsData = [];

// Add these variables at the top of the file
var currentRenewablePage = 1;
const RENEWABLE_PAGE_SIZE = 20;

// Column definitions with their expected data types
const RENEWABLE_COLUMN_DEFINITIONS = {
    "License No": { type: "STRING" },
    "Agent Name": { type: "STRING" },
    "City": { type: "FIXED_VALUES" },
    "Document Type": { type: "FIXED_VALUES" },
    "Validity Period": { type: "INT" },
    "Agent Process Date": { type: "DATE" },
    "New Document Number": { type: "STRING" },
    // "Last Renewal Date": { type: "DATE" },
    // "Next Expiry Date": { type: "DATE" },
    "Start Date": { type: "DATE" },
    "End Date": { type: "DATE" },
    "Receipt Document Date (from agent)": { type: "STRING" },
    "Remarks": { type: "STRING" },
    "Call Driver Date": { type: "DATE" },
    "Handover Document Date": { type: "DATE" },
    "Invoice No": { type: "STRING" },
    "Document Cost Amount": { type: "CURRENCY" },
    // "Open Cost": { type: "CURRENCY" },
    "Opsen Cost": { type: "CURRENCY" },
    "Surety Bond": { type: "CURRENCY" },
    "Admin Amount": { type: "CURRENCY" },
    "Penalty Amount": { type: "CURRENCY" },
    "Missing STNK Amount": { type: "CURRENCY" },
    "Agent Fee": { type: "CURRENCY" },
    "Vat Amount": { type: "CURRENCY" },
    "Total Cost": { type: "CURRENCY" }
};

// Required headers from the template
const RENEWABLE_REQUIRED_HEADERS = Object.keys(RENEWABLE_COLUMN_DEFINITIONS);

function validateRenewableDataType(value, expectedType) {
    if (value === undefined || value === null || value === "") {
        return true; // Allow empty values
    }

    switch (expectedType) {
        case "STRING":
            return true; // Skip validation for STRING type
        case "FIXED_VALUES":
            return typeof value === "string" || value instanceof String;
        case "INT":
            return Number.isInteger(Number(value));
        case "DATE":
            // Check for YYYY-MM-DD format
            const dateFormatRegex = /^\d{4}-\d{2}-\d{2}$/;
            if (!dateFormatRegex.test(value)) {
                return false;
            }
            // Validate if it's a valid date
            const date = new Date(value);
            return date instanceof Date && !isNaN(date) && date.toISOString().slice(0, 10) === value;
        case "CURRENCY":
            return !isNaN(Number(value));
        default:
            return true;
    }
}

function validateRenewableHeaders(headers) {
    let missingHeaders = [];
    RENEWABLE_REQUIRED_HEADERS.forEach(requiredHeader => {
        if (!headers.includes(requiredHeader)) {
            missingHeaders.push(requiredHeader);
        }
    });
    return missingHeaders;
}

function validateRenewableRowData(row, headers) {
    let errors = [];
    headers.forEach((header, index) => {
        if (RENEWABLE_COLUMN_DEFINITIONS[header]) {
            const expectedType = RENEWABLE_COLUMN_DEFINITIONS[header].type;
            const value = row[index];
            if (!validateRenewableDataType(value, expectedType)) {
                if (expectedType === "CURRENCY") {
                    errors.push(`Invalid number in column "${header}". Got "${value}"`);
                } else {
                    errors.push(`Invalid data type in column "${header}". Expected ${expectedType}, got ${value}`);
                }
            }
        }
    });
    return errors;
}

function attachVehicleRenewableDocuments() {
    // Create a dialog
    var uploadDialog = new sap.m.Dialog({
        title: "Upload Vehicle Renewable Documents",
        contentWidth: "400px",
        content: [
            new sap.m.VBox({
                items: [
                    new sap.m.Text({
                        text: "Please select an Excel file containing vehicle renewable documents data.",
                        wrapping: true
                    }).addStyleClass("sapUiSmallMarginBottom"),
                    new sap.m.HBox({
                        items: [
                            new sap.m.Text({
                                text: "No file selected",
                                wrapping: true
                            }).addStyleClass("sapUiTinyMarginEnd"),
                            new sap.m.Button({
                                text: "Browse",
                                type: "Emphasized",
                                press: function() {
                                    var fileInput = document.createElement('input');
                                    fileInput.type = 'file';
                                    fileInput.accept = '.xls, .xlsx';
                                    
                                    fileInput.onchange = function(e) {
                                        var file = e.target.files[0];
                                        if (file) {
                                            // Update the text to show selected file name
                                            uploadDialog.getContent()[0].getItems()[0].setText("Selected file: " + file.name);
                                            
                                            // Enable the Upload button
                                            uploadDialog.getButtons()[0].setEnabled(true);
                                            
                                            // Store the file in the dialog for later use
                                            uploadDialog.file = file;
                                        }
                                    };
                                    fileInput.click();
                                }
                            })
                        ]
                    })
                ]
            }).addStyleClass("sapUiSmallMargin")
        ],
        beginButton: new sap.m.Button({
            text: "Upload",
            enabled: false, // Initially disabled until file is selected
            press: function() {
                var file = uploadDialog.file;
                if (!file) {
                    sap.m.MessageToast.show("Please select a file first");
                    return;
                }

                // Show busy dialog
                var busyDialog = new sap.m.BusyDialog({
                    title: "Processing",
                    text: "Validating file contents..."
                });
                busyDialog.open();

                var reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        var data = new Uint8Array(e.target.result);
                        var workbook = XLSX.read(data, { type: 'array' });
                        
                        // Get the first sheet
                        var firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                        
                        // Get headers from the first row
                        var range = XLSX.utils.decode_range(firstSheet['!ref']);
                        var headers = [];
                        for (let C = range.s.c; C <= range.e.c; ++C) {
                            let cell = firstSheet[XLSX.utils.encode_cell({r: 0, c: C})];
                            headers.push(cell ? cell.v : undefined);
                        }

                        // Validate headers
                        let missingHeaders = validateRenewableHeaders(headers);
                        
                        if (missingHeaders.length > 0) {
                            busyDialog.close();
                            sap.m.MessageBox.error(
                                "The following required headers are missing in the uploaded file:\n\n" +
                                missingHeaders.join("\n"),
                                {
                                    title: "Invalid File Format"
                                }
                            );
                            return;
                        }

                        // Store data in JSON format
                        renewableDocsData = [];
                        
                        // Validate data types for each row and store valid data
                        let dataErrors = [];
                        for (let R = 1; R <= range.e.r; ++R) {
                            let row = [];
                            let rowData = {};
                            
                            for (let C = range.s.c; C <= range.e.c; ++C) {
                                let cell = firstSheet[XLSX.utils.encode_cell({r: R, c: C})];
                                let value = cell ? cell.v : undefined;
                                row.push(value);
                                rowData[headers[C]] = value;
                            }
                            
                            let rowErrors = validateRenewableRowData(row, headers);
                            if (rowErrors.length > 0) {
                                dataErrors.push(`Row ${R + 1}: ${rowErrors.join(", ")}`);
                            } else {
                                renewableDocsData.push(rowData);
                            }
                        }

                        busyDialog.close();

                        if (dataErrors.length > 0) {
                            sap.m.MessageBox.error(
                                "Data validation errors found:\n\n" + dataErrors.join("\n"),
                                {
                                    title: "Data Validation Error"
                                }
                            );
                        } else {
                            // If validation successful, proceed with API call
                            var formData = new FormData();
                            formData.append("file", file);
                            formData.append("email", emailUser);

                            // Show upload progress
                            var busyUploadDialog = new sap.m.BusyDialog({
                                title: "Uploading",
                                text: "Uploading file to server..."
                            });
                            busyUploadDialog.open();

                            $.ajax({
                                // url: "https://grab-prime-api-stg.azurewebsites.net/api/v1/upload/bulk_upload_documents",
                                url: `${jrs_go_api_url_name1}/upload/bulk_upload_documents`,
                                method: 'POST',
                                data: formData,
                                processData: false,
                                contentType: false,
                                headers: {
                                    'X-API-Key': jrs_go_api_key,
                                    'accept': 'application/json'
                                },
                                success: function(response) {
                                    busyUploadDialog.close();
                                    uploadDialog.close();
                                    sap.m.MessageToast.show("File uploaded successfully!");
                                    // Refresh the table data
                                    loadRenewableDocuments();
                                },
                                error: function(xhr, status, error) {
                                    busyUploadDialog.close();
                                    console.error("Upload failed:", xhr.responseJSON);
                                    let errorMessage = "Upload failed";
                                    
                                    // Try to get more specific error message from response
                                    if (xhr.responseJSON && xhr.responseJSON.status) {
                                        errorMessage += ": " + xhr.responseJSON.status;
                                    } else if (error) {
                                        errorMessage += ": " + error;
                                    }
                                    
                                    sap.m.MessageBox.error(errorMessage, {
                                        title: "Upload Error"
                                    });
                                }
                            });
                        }

                    } catch (error) {
                        busyDialog.close();
                        console.error("Error processing file:", error);
                        sap.m.MessageBox.error(
                            "Error processing file. Please make sure you're uploading a valid Excel file.",
                            {
                                title: "Error"
                            }
                        );
                    }
                };
                reader.readAsArrayBuffer(file);
            }
        }),
        endButton: new sap.m.Button({
            text: "Cancel",
            press: function() {
                uploadDialog.close();
            }
        }),
        afterClose: function() {
            uploadDialog.destroy();
        }
    });

    uploadDialog.open();
}

// Function to create the documents table
function createRenewableDocumentsTable() {
    // Create a container for the table with both horizontal and vertical scroll
    var oRenewableScrollContainer = new sap.m.ScrollContainer({
        horizontal: true,
        vertical: true,
        width: "100%",
        height: "calc(100vh - 100px)", // Adjust height to fill screen minus header
        content: []
    }).addStyleClass("renewableScrollContainer");

    // Create columns based on RENEWABLE_COLUMN_DEFINITIONS
    var aColumns = Object.keys(RENEWABLE_COLUMN_DEFINITIONS).map(function(columnKey) {
        return new sap.m.Column({
            width: columnKey === "Document Type" ? "100px" : 
                   columnKey === "Total Cost" ? "150px" : "200px",
            minScreenWidth: "30px",
            demandPopin: true,
            header: new sap.m.Label({ 
                text: columnKey,
                wrapping: true,
                design: "Bold",
                textAlign: "Center"
            }).addStyleClass("wrapHeader centerText"),
            hAlign: "Center" // Center align all columns
        });
    });

    // Create the table with fixed layout
    var oRenewableTable = new sap.m.Table("renewableDocsTable", {
        columns: aColumns,
        sticky: ["HeaderToolbar", "ColumnHeaders"],
        mode: "None",
        fixedLayout: true,
        width: "100%",
        growing: true,
        growingThreshold: 500,
        growingScrollToLoad: true
    }).addStyleClass("customTable");

    // Add the table to the scroll container
    oRenewableScrollContainer.addContent(oRenewableTable);

    // Create a VBox to contain both ScrollContainer and Load More button
    var oVBox = new sap.m.VBox({
        items: [
            oRenewableScrollContainer,
            new sap.m.HBox({
                justifyContent: "Center",
                width: "100%",
                items: [
                    new sap.m.Button("renewableLoadMoreBtn", {
                        text: "Load More Rows",
                        visible: false,
                        press: function() {
                            loadRenewableDocuments(currentRenewablePage + 1, true);
                        }
                    }).addStyleClass("sapUiSmallMarginTop sapUiSmallMarginBottom")
                ]
            })
        ]
    });

    // Update CSS styles
    var style = document.createElement('style');
    style.textContent = `
        .renewableScrollContainer {
            margin: 0;
            border: 1px solid #e5e5e5;
            height: 100% !important;
        }
        .customTable {
            margin: 0;
            width: 100%;
        }
        .customTable .sapMListTbl {
            table-layout: fixed;
            width: 100%;
            min-width: max-content;
        }
        .customTable .sapMListTblCell {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .customTable .sapMListTblHeader {
            white-space: nowrap;
        }
        /* Ensure text alignment for currency values */
        .customTable .sapMListTblCell:last-child .sapMText {
            text-align: right !important;
            padding-right: 8px !important;
            display: block !important;
        }
    `;
    document.head.appendChild(style);

    return oVBox;
}

function initRenewableDocuments() {
    // Create toolbar with bulk upload button and search field
    var oRenewableToolbar = new sap.m.Toolbar({
        content: [
            new sap.m.SearchField({
                id: "renewableSearchField",
                width: "250px",
                placeholder: "Search License No...",
                liveChange: function(oEvent) {
                    var sQuery = oEvent.getParameter("newValue");
                    var oTable = sap.ui.getCore().byId("renewableDocsTable");
                    var oBinding = oTable.getBinding("items");
                    
                    if (sQuery) {
                        var oFilter = new sap.ui.model.Filter(
                            "license_no",
                            sap.ui.model.FilterOperator.Contains,
                            sQuery
                        );
                        
                        oBinding.filter(oFilter);
                    } else {
                        oBinding.filter([]);
                    }
                }
            }),
            new sap.m.ToolbarSpacer(),
            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 Template",
                            icon: "sap-icon://download",
                            press: function() {
                                window.open("assets/renewable.xlsx", "_blank");
                            }
                        }),
                        new sap.m.MenuItem({
                            text: "Upload Excel",
                            icon: "sap-icon://upload",
                            press: function() {
                                attachVehicleRenewableDocuments();
                            }
                        })
                    ]
                })
            }),
            new sap.m.Button({
                icon: "sap-icon://filter",
                type: "Transparent",
                press: function() {
                    populateRenewableFilters();
                    oRenewableFilterDialog.open();
                }
            })
        ]
    }).addStyleClass("toolbarMargin");

    // Create the table
    var oRenewableTable = createRenewableDocumentsTable();

    // Create main section with toolbar and table in separate subsections
    var oRenewableSection = new sap.uxap.ObjectPageSection({
        subSections: [
            new sap.uxap.ObjectPageSubSection({
                blocks: [oRenewableToolbar]
            }).addStyleClass("reducedPadding"),
            new sap.uxap.ObjectPageSubSection({
                blocks: [oRenewableTable]
            })
        ]
    });

    // Add section to page layout
    oRenewablePageLayout.addSection(oRenewableSection);

    // Set header title with reduced margins
    oRenewablePageLayout.setHeaderTitle(
        new sap.uxap.ObjectPageDynamicHeaderTitle({
            heading: new sap.m.Title({ text: "Vehicle Renewable Documents" })
        })
    ).addStyleClass("reducedHeaderMargin");

    // Add custom CSS for reduced spacing
    var style = document.createElement('style');
    style.textContent = `
        .reducedHeaderMargin .sapUxAPObjectPageHeaderContent {
            padding-top: 0.5rem !important;
            padding-bottom: 0.5rem !important;
        }
        .reducedPadding {
            padding-top: 0 !important;
        }
        .toolbarMargin {
            margin-top: 0.5rem !important;
        }
        .sapUxAPObjectPageLayout-Std-Desktop .sapUxAPBlockContainer {
            padding: 0.5rem 0 !important;
        }
        .sapUxAPObjectPageHeaderContent {
            padding-top: 0 !important;
        }
        .sapUxAPObjectPageSection {
            margin-top: 0 !important;
        }
    `;
    document.head.appendChild(style);

    // Load initial data
    loadRenewableDocuments();
}




function decodeRenewableValue(encodedValue) {
    try {
        // Early return for invalid values
        if (encodedValue === null || encodedValue === undefined || encodedValue === '') {
            return '';
        }

        // Safely convert to string, handling non-string inputs
        let value = (encodedValue || '').toString().trim();

        // Early return for empty strings after trim
        if (!value) {
            return '';
        }

        // Try base64 decoding first
        try {
            let decodedValue = atob(value);
            let numericValue = parseFloat(decodedValue);
            if (!isNaN(numericValue)) {
                return numericValue.toLocaleString('id-ID');
            }
        } catch (e) {
            // Silently handle base64 decode errors
        }

        // Try direct numeric conversion if base64 fails
        let numericValue = parseFloat(value);
        if (!isNaN(numericValue)) {
            return numericValue.toLocaleString('id-ID');
        }

        // Return original value if all conversions fail
        return value;
    } catch (error) {
        // Just return empty string on any error
        return '';
    }
}

// Add this function to load vehicle renewable documents
function loadRenewableDocuments(page = 1, append = false) {
    var oRenewableTable = sap.ui.getCore().byId("renewableDocsTable");
    var oRenewableLoadMoreBtn = sap.ui.getCore().byId("renewableLoadMoreBtn");
    
    if (!oRenewableTable) {
        console.error("Table not found");
        return;
    }

    oRenewableTable.setBusy(true);

    $.ajax({
        url: `${jrs_go_api_url_name}/vehicle/documents/get_all_documents?master_email=${emailUser}&page=${page}&page_size=${RENEWABLE_PAGE_SIZE}`,
        method: 'GET',
        headers: {
            'X-API-Key': jrs_go_api_key,
            'accept': 'application/json'
        },
        success: function(response) {
            try {
                var oModel = oRenewableTable.getModel();
                var existingData = [];

                if (append && oModel) {
                    existingData = oModel.getProperty("/modelData") || [];
                }

                var newData = response.data.data;
            
                var combinedData = append ? existingData.concat(newData) : newData;
                
                if (!oModel) {
                    oModel = new sap.ui.model.json.JSONModel();
                }
               
                oModel.setData({ modelData: combinedData });
                oModel.refresh(true);
                oRenewableTable.setModel(oModel);

                // Only bind items if this is the first load
                if (!append) {
                    oRenewableTable.bindItems({
                        path: "/modelData",
                        template: new sap.m.ColumnListItem({
                            cells: [
                                new sap.m.Text({ text: "{license_no}" }).addStyleClass("centerText"),
                                new sap.m.Text({ text: "{agent_name}" }).addStyleClass("centerText"),
                                new sap.m.Text({ text: "{city}" }).addStyleClass("centerText"),
                                new sap.m.Text({ text: "{document_type}" }).addStyleClass("centerText"),
                                new sap.m.Text({ text: "{validity_period}" }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text:{
                                        path: "agent_process_date",
                                            formatter: function(value) {
                                                return formatDateToYYYYMMDD(value);
                                            }
                                    }
                                }).addStyleClass("centerText"),
                                // new sap.m.Text({ text: "{agent_process_date}" }).addStyleClass("centerText"),
                                new sap.m.Text({ text: "{new_document_number}" }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text:{
                                        path: "start_date",
                                            formatter: function(value) {
                                                return formatDateToYYYYMMDD(value);
                                            }
                                    }
                                }).addStyleClass("centerText"),
                                // new sap.m.Text({ text: "{start_date}" }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text:{
                                        path: "end_date",
                                            formatter: function(value) {
                                                return formatDateToYYYYMMDD(value);
                                            }
                                    }
                                }).addStyleClass("centerText"),
                                // new sap.m.Text({ text: "{end_date}" }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text:{
                                        path: "receipt_document_date",
                                            formatter: function(value) {
                                                return formatDateToYYYYMMDD(value);
                                            }
                                    }
                                }).addStyleClass("centerText"),
                                // new sap.m.Text({ text: "{receipt_document_date}" }).addStyleClass("centerText"),
                                new sap.m.Text({ text: "{remarks}" }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text:{
                                        path: "call_driver_date",
                                            formatter: function(value) {
                                                return formatDateToYYYYMMDD(value);
                                            }
                                    }
                                }).addStyleClass("centerText"),
                                // new sap.m.Text({ text: "{call_driver_date}" }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text:{
                                        path: "handover_document_date",
                                            formatter: function(value) {
                                                return formatDateToYYYYMMDD(value);
                                            }
                                    }
                                }).addStyleClass("centerText"),
                                // new sap.m.Text({ text: "{handover_document_date}" }).addStyleClass("centerText"),
                                new sap.m.Text({ text: "{invoice_no}" }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text: {
                                        path: "document_cost_amount",
                                        formatter: function(value) {
                                            // return value ? "Rp " + decodeRenewableValue(value) : "";
                                            return value ? (decodeRenewableValue(value)):"0";
                                        }
                                    }
                                }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text: {
                                        path: "opsen_cost",
                                        formatter: function(value) {
                                            // return value ? "Rp " + decodeRenewableValue(value) : "";
                                            return value ? (decodeRenewableValue(value)):"0";
                                        }
                                    }
                                }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text: {
                                        path: "surety_bond",
                                        formatter: function(value) {
                                            // return value ? "Rp " + decodeRenewableValue(value) : "";
                                            return value ? (decodeRenewableValue(value)):"0";
                                        }
                                    }
                                }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text: {
                                        path: "admin_amount",
                                        formatter: function(value) {
                                            // return value ? "Rp " + decodeRenewableValue(value) : "";
                                            return value ? (decodeRenewableValue(value)):"0";
                                        }
                                    }
                                }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text: {
                                        path: "penalty_amount",
                                        formatter: function(value) {
                                            // return value ? "Rp " + decodeRenewableValue(value) : "";
                                            return value ? (decodeRenewableValue(value)):"0";
                                        }
                                    }
                                }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text: {
                                        path: "missing_stnk_amount",
                                        formatter: function(value) {
                                            // return value ? "Rp " + decodeRenewableValue(value) : "";
                                            return value ? (decodeRenewableValue(value)):"0";
                                        }
                                    }
                                }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text: {
                                        path: "agent_fee",
                                        formatter: function(value) {
                                            // return value ? "Rp " + decodeRenewableValue(value) : "";
                                            return value ? (decodeRenewableValue(value)):"0";
                                        }
                                    }
                                }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text: {
                                        path: "vat_amount",
                                        formatter: function(value) {
                                            // return value ? "Rp " + decodeRenewableValue(value) : "";
                                            return value ? (decodeRenewableValue(value)):"0";
                                        }
                                    }
                                }).addStyleClass("centerText"),
                                new sap.m.Text({ 
                                    text: {
                                        path: "total_cost",
                                        formatter: function(value) {
                                            // return value ? "Rp " + decodeRenewableValue(value) : "";
                                            return value ? (decodeRenewableValue(value)):"0";
                                        }
                                    }
                                }).addStyleClass("centerText")
                            ]
                        })
                    });
                }

                // Update current page
                currentRenewablePage = page;

                // Update Load More button text and visibility
                if (oRenewableLoadMoreBtn) {
                    var totalRecords = response.data.total_records;
                    var currentlyShown = combinedData.length;
                    
                    if (currentlyShown < totalRecords) {
                        oRenewableLoadMoreBtn.setText(`Load More Rows (${currentlyShown} of ${totalRecords})`);
                        oRenewableLoadMoreBtn.setVisible(true);
                    } else {
                        oRenewableLoadMoreBtn.setVisible(false);
                    }
                }

                oRenewableTable.setBusy(false);

                // Add this CSS to ensure headers are wrapped and content is centered
                var style = document.createElement('style');
                style.textContent = `
                    .customTable .sapMListTblHeader {
                        white-space: normal !important;
                        height: auto !important;
                        padding: 8px !important;
                        text-align: center !important;
                    }
                    .wrapHeader {
                        white-space: normal !important;
                        height: auto !important;
                        line-height: 1.2 !important;
                    }
                    .customTable .sapMColumnHeader {
                        height: auto !important;
                        padding: 8px !important;
                    }
                    .customTable .sapMTableTH {
                        vertical-align: middle !important;
                        height: auto !important;
                        padding: 8px !important;
                        text-align: center !important;
                    }
                    /* Center alignment for all text */
                    .centerText {
                        text-align: center !important;
                        justify-content: center !important;
                        align-items: center !important;
                        display: block !important;
                    }
                    /* Center alignment for table cells */
                    .customTable .sapMListTblCell {
                        text-align: center !important;
                        vertical-align: middle !important;
                    }
                    /* Ensure currency values remain centered */
                    .customTable .sapMListTblCell .sapMText {
                        text-align: center !important;
                        display: block !important;
                    }
                `;
                document.head.appendChild(style);

            } catch (error) {
                console.error("Error processing response:", error);
                oRenewableTable.setBusy(false);
                sap.m.MessageBox.error("Error processing data. Please try again.");
            }
        },
        error: function(xhr, status, error) {
            console.error("API call failed:", error);
            oRenewableTable.setBusy(false);
            sap.m.MessageBox.error("Failed to load data: " + error);
        }
    });
}

var carInsuranceRenewalJSONArray = []
function getCarInsuranceRenewal(){
    Car_Insurance_Renewal.where({master_email:emailUser}).take(2000).read().done(function (result) {
        carInsuranceRenewalJSONArray = result;
    })
}

// Add this function to populate filter dropdowns
function populateRenewableFilters() {
    try {
        var oRenewableTable = sap.ui.getCore().byId("renewableDocsTable");
        var oModel = oRenewableTable.getModel();
        if (!oModel) return;
        
        var aData = oModel.getProperty("/modelData");
        if (!aData) return;

        // Get unique values
        var uniqueLicenseNos = [...new Set(aData
            .map(item => item.license_no)
            .filter(item => item && item.trim() !== "")
        )].sort();

        var uniqueAgentNames = [...new Set(aData
            .map(item => item.agent_name)
            .filter(item => item && item.trim() !== "")
        )].sort();

        var uniqueCities = [...new Set(aData
            .map(item => item.city)
            .filter(item => item && item.trim() !== "")
        )].sort();
       
        var uniqueDocType = [...new Set(aData
            .map(item => item.document_type)
            .filter(item => item && item.trim() !== "")
        )].sort();

        // Get the ComboBoxes
        var comboBoxes = oRenewableFilterDialog.getContent()[0].getItems()
            .filter(item => item instanceof sap.m.ComboBox);
        
        // Clear and populate ComboBoxes
        comboBoxes.forEach((comboBox, index) => {
            comboBox.removeAllItems();
            let items = index === 0 ? uniqueLicenseNos :
                       index === 1 ? uniqueAgentNames :
                       index === 2 ? uniqueCities :
                       uniqueDocType;
            
            items.forEach(item => {
                comboBox.addItem(new sap.ui.core.Item({
                    key: item,
                    text: item
                }));
            });
        });

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

// Create the filter dialog
var oRenewableFilterDialog = new sap.m.Dialog({
    title: "Filter Vehicle Renewable Documents",
    contentWidth: "40%",
    content: [
        new sap.m.VBox({
            width: "100%",
            items: [
                new sap.m.Label({ text: "License No:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select License No"
                }),
                
                new sap.m.Label({ text: "Agent Name:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Agent Name"
                }),
                
                new sap.m.Label({ text: "City:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select City"
                }),
                
                new sap.m.Label({ text: "Document Type:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Document Type"
                }),

                new sap.m.Label({ text: "Start Date:", design: "Bold", required: false }),
                new sap.m.DatePicker({
                    displayFormat: "yyyy-MM-dd" ,valueFormat: "yyyy-MM-dd",
                    width: "94%",
                    placeholder: "Select Start Date"
                }),

                new sap.m.Label({ text: "End Date:", design: "Bold", required: false }),
                new sap.m.DatePicker({
                    displayFormat: "yyyy-MM-dd" ,valueFormat: "yyyy-MM-dd",
                    width: "94%",
                    placeholder: "Select End Date"
                }),

            ]
        }).addStyleClass("sapUiSmallMargin")
    ],
    buttons: [
        new sap.m.Button({
            icon: "sap-icon://clear-filter",
            text: "Clear Filter",
            press: function() {
                clearRenewableFilters();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://decline",
            text: "Cancel",
            press: function() {
                oRenewableFilterDialog.close();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://filter",
            text: "Apply Filter",
            type: "Emphasized",
            press: function() {
                // Get the current filters if they exist
                var oTable = sap.ui.getCore().byId("renewableDocsTable");
                var oBinding = oTable.getBinding("items");
                var aCurrentFilters = oBinding ? oBinding.aFilters : [];
                
                // Get ComboBoxes
                var aComboBoxes = oRenewableFilterDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.ComboBox;
                });
             
                // Create new filters array
                var aNewFilters = [];
                
                // Add filters for ComboBox fields
                var comboBoxFields = ["license_no", "agent_name", "city","document_type"];
                aComboBoxes.forEach(function(oComboBox, index) {
                    var sValue = oComboBox.getSelectedKey();
                    if (sValue) {
                        var fieldName = comboBoxFields[index];
                        // Remove existing filter for this field if it exists
                        aCurrentFilters = aCurrentFilters.filter(f => f.sPath !== fieldName);
                        // Add new filter
                        aNewFilters.push(new sap.ui.model.Filter(
                            fieldName,
                            sap.ui.model.FilterOperator.EQ,
                            sValue
                        ));
                    }
                });
                

                // Get DatePickers
                var aDatePickers = oRenewableFilterDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.DatePicker;
                });

                // Filter based on date range
                var oStartDate = aDatePickers[0].getValue();
                var oEndDate = aDatePickers[1].getValue();
   
                   if (oStartDate) {
                       aCurrentFilters = aCurrentFilters.filter(f => f.sPath !== "start_date");
                       var sStartDateStr = oStartDate + "T00:00:00Z";
                       aNewFilters.push(new sap.ui.model.Filter("start_date", sap.ui.model.FilterOperator.EQ, sStartDateStr));
                   }
   
                   if (oEndDate) {
                       aCurrentFilters = aCurrentFilters.filter(f => f.sPath !== "end_date");
                       var sEndDateStr = oEndDate + "T00:00:00Z";
                       aNewFilters.push(new sap.ui.model.Filter("end_date", sap.ui.model.FilterOperator.EQ, sEndDateStr));
                   }
   



                // Combine current and new filters
                var aAllFilters = aCurrentFilters.concat(aNewFilters);
                
                if (oBinding) {
                    if (aAllFilters.length > 0) {
                        // Create a combined filter with AND condition
                        var oCombinedFilter = new sap.ui.model.Filter({
                            filters: aAllFilters,
                            and: true
                        });
                        
                        // Apply the combined filter
                        oBinding.filter(oCombinedFilter);
                    } else {
                        oBinding.filter([]);
                    }
                }
                
                oRenewableFilterDialog.close();
            }
        })
    ]
}).addStyleClass("sapUiSizeCompact");

// Update clear filters function
function clearRenewableFilters() {
    try {
        var filterContent = oRenewableFilterDialog.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 datePickerInput = filterContent.getItems().filter(function(item) {
            return item instanceof sap.m.DatePicker;
        });
        datePickerInput.forEach(function(input) {
            input.setValue("");
        });

        // Clear the table binding filter
        var oTable = sap.ui.getCore().byId("renewableDocsTable");
        var oBinding = oTable.getBinding("items");
        if (oBinding) {
            oBinding.filter([]);
        }

        // Clear the search field
        var oSearchField = sap.ui.getCore().byId("renewableSearchField");
        if (oSearchField) {
            oSearchField.setValue("");
        }

        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.");
    }
}



// // Initialize when document is ready
// jQuery(document).ready(function() {
//     // initRenewableDocuments();
// });
