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

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

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

// Add these variables at the top of the file after vehicleDocumentsData declaration
var currentDocPage = 1;
const DOCS_PAGE_SIZE = 20;

// Column definitions with their expected data types
const COLUMN_DEFINITIONS = {
    "License No": { type: "STRING" },
    "Insurance Company ID": { type: "STRING" },
    "Insurance Company Name": { type: "STRING" },
    "Insurance Policy Number": { type: "STRING" },
    "City": { type: "FIXED_STRING" },
    "Document Type": { type: "FIXED_STRING" },
    "Validity Period": { type: "INT" },
    "Agent Process Date": { type: "DATE" },
    "Start Date": { type: "DATE" },
    "End Date": { type: "DATE" },
    "Receipt Document Date (from agent)": { type: "STRING" },
    "Insurance Type": { type: "FIXED_VALUES" },
    "Remarks": { type: "STRING" },
    "Invoice No": { type: "STRING" },
    "Invoice Date": { type: "DATE" },
    "Total Sum Insurance": { type: "CURRENCY" },
    "Third Party Liability": { type: "CURRENCY" },
    "Personal Accident Driver": { type: "FLOAT" },
    "Personal Accident Passenger": { type: "FLOAT" }, //New Added
    "Towing Allowance": { type: "STRING" },
    "Ext - EQVT": { type: "FLOAT" },
    "Ext - Typhoon": { type: "FLOAT" },
    "Ext - SRCC": { type: "FLOAT" },
    "Ext - TBOD": { type: "FLOAT" },
    "Authorize Workshop": { type: "STRING" },
    "Premium Amount": { type: "CURRENCY" },
    "Vat": { type: "CURRENCY" },
    "Total Cost": { type: "CURRENCY" }
};

// Required headers from the template
const REQUIRED_HEADERS = Object.keys(COLUMN_DEFINITIONS);

function validateDataType(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_STRING":
            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));
        case "FIXED_VALUES":
            return typeof value === "string" || value instanceof String;
        case "CURRENCY":
            return typeof value == 'number'
        default:
            return true;
    }
}

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

function validateRowData(row, headers) {
    let errors = [];
    headers.forEach((header, index) => {
        if (COLUMN_DEFINITIONS[header]) {
            const expectedType = COLUMN_DEFINITIONS[header].type;
            const value = row[index];
            if (!validateDataType(value, expectedType)) {
                if (expectedType === "CURRENCY") {
                    errors.push(`Invalid number in column "${header}". Got "${value}"`);
                } else if (expectedType === "DATE") {
                    errors.push(`Invalid date format in column "${header}". Expected YYYY-MM-DD format, got "${value}"`);
                } else {
                    errors.push(`Invalid data type in column "${header}". Expected ${expectedType}, got "${value}"`);
                }
            }
        }
    });
    return errors;
}

function attachVehicleDocuments() {
    // Create a dialog
    var uploadDialog = new sap.m.Dialog({
        title: "Upload Vehicle Documents",
        contentWidth: "400px",
        content: [
            new sap.m.VBox({
                items: [
                    new sap.m.Text({
                        text: "Please select an Excel file containing vehicle 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 = validateHeaders(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
                        vehicleDocumentsData = [];
                        
                        // 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 = validateRowData(row, headers);
                            if (rowErrors.length > 0) {
                                dataErrors.push(`Row ${R + 1}: ${rowErrors.join(", ")}`);
                            } else {
                                vehicleDocumentsData.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 uploadDialog1 = new sap.m.BusyDialog({
                                title: "Uploading",
                                text: "Uploading file to server..."
                            });
                            uploadDialog1.open();

                            $.ajax({
                                // url: "https://grab-prime-api-stg.azurewebsites.net/api/v1/upload/bulk_upload_insurance",
                                url: `${jrs_go_api_url_name1}/upload/bulk_upload_insurance`,
                                method: 'POST',
                                data: formData,
                                processData: false,
                                contentType: false,
                                headers: {
                                    'X-API-Key': jrs_go_api_key,
                                    'accept': 'application/json'
                                },
                                success: function(response) {
                                    uploadDialog1.close();
                                    sap.m.MessageToast.show("File uploaded successfully!");
                                    uploadDialog.close();
                                    loadVehicleInsuranceDocuments();
                                    // uploadDialog.getParent().close();
                                    // Refresh the table data
                                    //getCarInsuranceRenewal();
                                },
                                error: function(xhr, status, error) {
                                    uploadDialog1.close();
                                    console.error("Upload failed:", xhr.responseJSON.status);
                                    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 createDocumentsTable() {
    // Create a container for the table with both horizontal and vertical scroll
    var oInsuranceScrollContainer = new sap.m.ScrollContainer({
        horizontal: true,
        vertical: true,
        width: "100%",
        height: "calc(100vh - 100px)", // Adjust height to fill screen minus header
        content: []
    }).addStyleClass("insuranceScrollContainer");

    // Create columns based on COLUMN_DEFINITIONS
    var aColumns = Object.keys(COLUMN_DEFINITIONS).map(function(columnKey) {
        var oColumn = 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" // Center align header text
            }).addStyleClass("wrapHeader centerText"),
            hAlign: "Center" // Center align column content
        });

        return oColumn;
    });

    // Create the table with fixed layout
    var oTable = new sap.m.Table("vehicleDocumentsTable", {
        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
    oInsuranceScrollContainer.addContent(oTable);

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

    // Update CSS styles
    var style = document.createElement('style');
    style.textContent = `
        .insuranceScrollContainer {
            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;
            vertical-align: middle !important;
        }
        /* Header wrapping styles */
        .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:last-child .sapMText {
            text-align: center !important;
            display: block !important;
        }
    `;
    document.head.appendChild(style);

    // Update the item binding template to center-align all cells
    oTable.bindItems({
        path: "/modelData",
        template: new sap.m.ColumnListItem({
            cells: [
                new sap.m.Text({ text: "{license_no}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{insurance_company_id}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{insurance_company_name}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{insurance_policy_number}" }).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: "{agent_process_date}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{start_date}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{end_date}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{receipt_document_date}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{insurance_type}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{remarks}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{invoice_no}" }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{invoice_date}" }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "total_sum_insurance",
                        formatter: function(value) {
                            // return value ? "Rp " + decodeValue(value) : "";
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                            return value ? formatIDRWithoutSymbol(value) : "0";
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "third_party_liability",
                        formatter: function(value) {
                            // return value ? "Rp " + decodeValue(value) : "";
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                            return value ? formatIDRWithoutSymbol(value) : "0";
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "personal_accident_driver",
                        formatter: function(value) {
                            // return decodeValue(value) || 0;
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0"
                            return value ? formatIDRWithoutSymbol(value): "0"
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "personal_accident_passenger",
                        formatter: function(value) {
                            // return decodeValue(value) || 0;
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0"
                            return value ? formatIDRWithoutSymbol(value): "0"
                        }
                    }
                }).addStyleClass("centerText"),
                // new sap.m.Text({ text: "{towing_allowance}" }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "towing_allowance",
                        formatter: function(value) {
                            // return decodeValue(value) || 0;
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0"
                            return value ? formatIDRWithoutSymbol(value): "0"
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "ext_eqvt",
                        formatter: function(value) {
                            // return decodeValue(value) || 0;
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0"
                            return value ? formatIDRWithoutSymbol(value): "0"
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "ext_typhoon",
                        formatter: function(value) {
                            // return decodeValue(value) || 0;
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0"
                            return value ? formatIDRWithoutSymbol(value): "0"
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "ext_srcc",
                        formatter: function(value) {
                            // return decodeValue(value) || 0;
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0"
                            return value ? formatIDRWithoutSymbol(value): "0"
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "ext_tbod",
                        formatter: function(value) {
                            // return decodeValue(value) || 0;
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0"
                            return value ? formatIDRWithoutSymbol(value): "0"
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ text: "{authorize_workshop}" }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "premium_amount",
                        formatter: function(value) {
                            // return value ? "Rp " + decodeValue(value) : "";
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                            return value ? formatIDRWithoutSymbol(value) : "0";
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "vat_amount",
                        formatter: function(value) {
                            // return value ? "Rp " + decodeValue(value) : "";
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                            return value ? formatIDRWithoutSymbol(value) : "0";
                        }
                    }
                }).addStyleClass("centerText"),
                new sap.m.Text({ 
                    text: {
                        path: "total_cost",
                        formatter: function(value) {
                            // return value ? "Rp " + decodeValue(value) : "";
                            // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                            return value ? formatIDRWithoutSymbol(value) : "0";
                        }
                    }
                }).addStyleClass("centerText")
                
            ]
        })
    });

    return oVBox;
}

// Initialize Vehicle Documents
function initVehicleDocuments() {
    // Create toolbar with bulk upload button and search field
    var oToolbar = new sap.m.Toolbar({
        content: [
            new sap.m.SearchField({
                id: "vehicleDocsSearchField",
                width: "250px",
                placeholder: "Search License No...",
                liveChange: function(oEvent) {
                    var sQuery = oEvent.getParameter("newValue");
                    var oTable = sap.ui.getCore().byId("vehicleDocumentsTable");
                    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 Upload",
                            icon: "sap-icon://download",
                            press: function() {
                                    window.open("assets/insurance.xlsx", "_blank");
                            }
                        }),
                        new sap.m.MenuItem({
                            text: "Upload Excel",
                            icon: "sap-icon://upload",
                            press: function() {
                                attachVehicleDocuments();
                            }
                        })
                    ]
                })
            }),
            new sap.m.Button({
                icon: "sap-icon://filter",
                type: "Transparent",
                press: function() {
                    populateInsuranceFilterDropdowns();
                    oInsuranceFilterDialog.open();
                }
            })
        ]
    });

    // Create the table
    var oTable = createDocumentsTable();

    // Create main section with toolbar and table in separate subsections
    var oMainSection = new sap.uxap.ObjectPageSection({
        subSections: [
            new sap.uxap.ObjectPageSubSection({
                blocks: [oToolbar]
            }),
            new sap.uxap.ObjectPageSubSection({
                blocks: [oTable]
            })
        ]
    });

    // Add section to page layout
    oVehicleDocPageLayout.addSection(oMainSection);

    // Set header title
    oVehicleDocPageLayout.setHeaderTitle(
        new sap.uxap.ObjectPageDynamicHeaderTitle({
            heading: new sap.m.Title({ text: "Vehicle Insurance Documents" })
        })
    );

    // Load initial data
    loadVehicleInsuranceDocuments();
}



// Update the loadVehicleInsuranceDocuments function to handle pagination
function loadVehicleInsuranceDocuments(page = 1, append = false) {
    var oTable = sap.ui.getCore().byId("vehicleDocumentsTable");
    var oLoadMoreButton = sap.ui.getCore().byId("docsLoadMoreButton");
    
    if (!oTable) {
        console.error("Table not found");
        return;
    }

    oTable.setBusy(true);
    
    $.ajax({
        url: `${jrs_go_api_url_name}/vehicle/insurance/get_all_insurance?master_email=${emailUser}&page=${page}&page_size=${DOCS_PAGE_SIZE}`,
        method: 'GET',
        headers: {
            'X-API-Key': jrs_go_api_key,
            'accept': 'application/json'
        },
        success: function(response) {

            try {
                var oModel = oTable.getModel();
                var existingData = [];

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


                var newData = response.data.data;
                if(newData != 'No data for current filters'){

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

                    // Only bind items if this is the first load
                    if (!append) {
                    // Bind items to table
                    oTable.bindItems({
                        path: "/modelData",
                        template: new sap.m.ColumnListItem({
                            cells: [
                                    new sap.m.Text({ text: "{license_no}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ text: "{insurance_company_id}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ text: "{insurance_company_name}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ text: "{insurance_policy_number}" }).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: "{start_date}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text:{
                                            path: "start_date",
                                                formatter: function(value) {
                                                    return formatDateToYYYYMMDD(value);
                                                }
                                        }
                                    }).addStyleClass("centerText"),
                                    // new sap.m.Text({ text: "{end_date}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text:{
                                            path: "end_date",
                                                formatter: function(value) {
                                                    return formatDateToYYYYMMDD(value);
                                                }
                                        }
                                    }).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: "{insurance_type}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ text: "{remarks}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ text: "{invoice_no}" }).addStyleClass("centerText"),
                                    // new sap.m.Text({ text: "{invoice_date}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text:{
                                            path: "invoice_date",
                                                formatter: function(value) {
                                                    return formatDateToYYYYMMDD(value);
                                                }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "total_sum_insurance",
                                            formatter: function(value) {
                                                // return value ? "Rp " + decodeValue(value) : "";
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                                                return value ? formatIDRWithoutSymbol(value) : "0";
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "third_party_liability",
                                            formatter: function(value) {
                                                // return value ? "Rp " + decodeValue(value) : "";
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                                                return value ? formatIDRWithoutSymbol(value) : "0";
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "personal_accident_driver",
                                            formatter: function(value) {
                                                // return decodeValue(value) || 0;
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)) :"0";
                                                return value ? formatIDRWithoutSymbol(value) :"0";
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "personal_accident_passenger",
                                            formatter: function(value) {
                                                // return decodeValue(value) || 0;
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)):"0";
                                                return value ? formatIDRWithoutSymbol(value):"0";
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    // new sap.m.Text({ text: "{towing_allowance}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "towing_allowance",
                                            formatter: function(value) {
                                                // return decodeValue(value) || 0;
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                                                return value ? formatIDRWithoutSymbol(value) : "0";
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "ext_eqvt",
                                            formatter: function(value) {
                                                // return decodeValue(value) || 0;
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                                                return value ? formatIDRWithoutSymbol(value) : "0";
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "ext_typhoon",
                                            formatter: function(value) {
                                                // return decodeValue(value) || 0;
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0";
                                                return value ? formatIDRWithoutSymbol(value): "0";
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "ext_srcc",
                                            formatter: function(value) {
                                                // return decodeValue(value) || 0;
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0";
                                                return value ? formatIDRWithoutSymbol(value): "0";
                                                
                                            }
                                        }
                                    }).addStyleClass("centerText"),      
                                    new sap.m.Text({ 
                                        text: {
                                            path: "ext_tbod",
                                            formatter: function(value) {
                                                // return decodeValue(value) || 0;
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)): "0"
                                                return value ? formatIDRWithoutSymbol(value): "0"
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ text: "{authorize_workshop}" }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            // path: "final_premium",
                                            path: "premium_amount",
                                            formatter: function(value) {
                                                // return value ? "Rp " + decodeValue(value) : "";
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                                                return value ? formatIDRWithoutSymbol(value) : "0";
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "vat_amount",
                                            formatter: function(value) {
                                                // return value ? "Rp " + decodeValue(value) : "";
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                                                return value ? formatIDRWithoutSymbol(value) : "0";
                                            }
                                        }
                                    }).addStyleClass("centerText"),
                                    new sap.m.Text({ 
                                        text: {
                                            path: "total_cost",
                                            formatter: function(value) {
                                                // return value ? "Rp " + decodeValue(value) : "";
                                                // return value ? formatIDRWithoutSymbol(decodeValue(value)) : "0";
                                                return value ? formatIDRWithoutSymbol(value) : "0";
                                            }
                                        }
                                    }).addStyleClass("centerText")             
                                ]
                            })
                        });
                    }

                    // Update current page
                    currentDocPage = page;
    
                    // Update Load More button text and visibility
                    if (oLoadMoreButton) {
                        var totalRecords = response.data.total_records;
                        var currentlyShown = combinedData.length;
                        
                        if (currentlyShown < totalRecords) {
                            oLoadMoreButton.setText(`Load More Rows (${currentlyShown} of ${totalRecords})`);
                            oLoadMoreButton.setVisible(true);
                        } else {
                            oLoadMoreButton.setVisible(false);
                        }
                    }
    
                }
                oTable.setBusy(false);
            } catch (error) {
                console.error("Error processing response:", error);
                oTable.setBusy(false);
                sap.m.MessageBox.error("Error processing data. Please try again.");
            }
        },
        error: function(xhr, status, error) {
            console.error("API call failed:", error);
            oTable.setBusy(false);
            sap.m.MessageBox.error("Failed to load data: " + error);
        }
    });
}

// Add this function to populate filter dropdowns
function populateInsuranceFilterDropdowns() {
    try {
        var oTable = sap.ui.getCore().byId("vehicleDocumentsTable");
        var oModel = oTable.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.insurance_company_name)
            .filter(item => item && item.trim() !== "")
        )].sort();

        var uniqueCities = [...new Set(aData
            .map(item => item.city)
            .filter(item => item && item.trim() !== "")
        )].sort();
  
        var uniqueInsurenceType = [...new Set(aData
            .map(item => item.insurance_type)
            .filter(item => item && item.trim() !== "")
        )].sort();
        
        var uniquePolicyNumber = [...new Set(aData
            .map(item => item.insurance_policy_number)
            .filter(item => item && item.trim() !== "")
        )].sort();

        // Get the ComboBoxes
        var comboBoxes = oInsuranceFilterDialog.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:
                       index === 3 ?  uniqueInsurenceType:
                       uniquePolicyNumber;
            
            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 oInsuranceFilterDialog = new sap.m.Dialog({
    title: "Filter Vehicle Insurance 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: "Insurance company Name:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Insurance company 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: "Insurance Type:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Insurance Type"
                }),
             
                new sap.m.Label({ text: "Policy Number:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Policy Number"
                }),

                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() {
                clearInsuranceFilters();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://decline",
            text: "Cancel",
            press: function() {
                oInsuranceFilterDialog.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("vehicleDocumentsTable");
                var oBinding = oTable.getBinding("items");
                var aCurrentFilters = oBinding ? oBinding.aFilters : [];
                
                // Get ComboBoxes
                var aComboBoxes = oInsuranceFilterDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.ComboBox;
                });
                
                // // Get Input fields
                // var aInputs = oInsuranceFilterDialog.getContent()[0].getItems().filter(function(item) {
                //     return item instanceof sap.m.Input;
                // });
                
                // Create new filters array
                var aNewFilters = [];
                
                // Add filters for ComboBox fields
                var comboBoxFields = ["license_no", "insurance_company_name", "city","insurance_type","insurance_policy_number"];
                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 = oInsuranceFilterDialog.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([]);
                    }
                }
                
                oInsuranceFilterDialog.close();
            }
        })
    ]
}).addStyleClass("sapUiSizeCompact");

// Update clear filters function
function clearInsuranceFilters() {
    try {
        var filterContent = oInsuranceFilterDialog.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("vehicleDocumentsTable");
        var oBinding = oTable.getBinding("items");
        if (oBinding) {
            oBinding.filter([]);
        }

        // Clear the search field
        var oSearchField = sap.ui.getCore().byId("vehicleDocsSearchField");
        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.");
    }
}

// Add this function to decode values
function decodeValue(encodedValue) {
    try {
        // For non-currency integer fields, just decode from base64
        if (!encodedValue) return "";
        
        // Try base64 decoding
        try {
            let decodedValue = atob(encodedValue);
            let numericValue = parseFloat(decodedValue);
            
            // For currency values, format with Rp and thousand separators
            if (encodedValue.startsWith('Rp ')) {
                return numericValue.toLocaleString('id-ID');
            }
            
            // For regular numbers, return as is
            return numericValue;
        } catch (e) {
            // If not base64 encoded, return as is
            return encodedValue;
        }
    } catch (error) {
        return encodedValue;
    }
}


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