// localStorage.removeItem('employeesLeaveData');

// Open the popup when clicking on the "New" button
document.getElementById('openPopupButton').addEventListener('click', function(event) {
    event.preventDefault(); // Prevent default behavior of the link (if any)
    // Show the popup by changing its display style
    document.getElementById('shift-employer-popup-overlay').style.display = 'block';
});

// Close the popup when clicking on the "Close" button inside the popup
document.getElementById('closePopup').addEventListener('click', function() {
    // Hide the popup by setting display to 'none'
    document.getElementById('leaveEmployerForm').reset();
    delete document.getElementById("employeeLeaveSave").dataset.editIndex;
    document.getElementById('leaveEmployeeName').disabled = false;
    document.getElementById('shift-employer-popup-overlay').style.display = 'none';
});

/**
 * ----------------------------- script for "View" button-------------------------------------------------------------------
 */

// Event listener for the "View" button in the RFQ Details table
document.getElementById('dataTable').addEventListener('click', function(event) {
    // Check if the clicked element is the view button
    if (event.target && event.target.id === 'employeeLeave-pdf') {
        const pdfUrl = event.target.dataset.pdfUrl; // Get the PDF URL from the button's data attribute
        if (pdfUrl) {
            // Set the PDF URL in the iframe for viewing
            document.getElementById('pdfViewer').src = pdfUrl;
            // Display the modal
            $('#pdfModal').modal('show');
        } else {
            alert("No PDF file found for this entry.");
        }
    }
});

/**
 * ----------------------------- script for import details-------------------------------------------------------------------
 */

// Trigger the modal when the Import button is clicked
document.getElementById('import-button').addEventListener('click', function() {
    $('#importModal').modal('show');
});

// Handle the Excel file import
document.getElementById('importDataBtn').addEventListener('click', function () {
    const fileInput = document.getElementById('excelFile');
    const file = fileInput.files[0];

    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            const data = e.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const sheet = workbook.Sheets[sheetName];
            const excelData = XLSX.utils.sheet_to_json(sheet);

            // Get the logged-in user
            const loggedUser = document.getElementById('logged_user').textContent.trim();

            // Convert Excel data to the required format
            const formattedData = excelData.map(row => {
                const leaveId = row['Leave ID'] || `leave-${row['Employee ID']}-${Date.now()}`;
                const leaveDate = (row['Requested On']);
                const status = row['Status'] || '';
                const requestedOn = excelDateToJSDate(leaveDate) || new Date().toISOString().split('T')[0]; // Current date

                let approvedBy = '-';
                let approvalDate = '-';

                if (status.toLowerCase() === "approved") {
                    approvedBy = row['Approved By'] || loggedUser;
                    approvalDate = excelDateToJSDate(row['Approval Date']) || requestedOn;
                }

                return {
                    leaveId,
                    employeeId: row['Employee ID'] || '',
                    employeeName: row['Employee Name'] || '',
                    department: row['Department'] || '',
                    leaveType: row['Leave Type'] || '',
                    leaveFrom: excelDateToJSDate(row['Leave From']) || '',
                    leaveTo: excelDateToJSDate(row['Leave To']) || '',
                    numberOfDays: row['Number of Days'] || '',
                    durationType: row['Duration Type'] || '',
                    status,
                    reasonForLeave: row['Reason'] || '',
                    requestedOn,
                    approvedBy,
                    approvalDate
                };
            });

            // Save data in localStorage, avoiding duplicates
            const existingData = JSON.parse(localStorage.getItem('employeesLeaveData')) || [];
            const mergedData = mergeLeaveData(existingData, formattedData);
            localStorage.setItem('employeesLeaveData', JSON.stringify(mergedData));

            // Reload the table with the new data
            window.location.reload();

            // Close the modal and notify the user
            $('#importModal').modal('hide');
            alert('Leave details imported successfully!');
        };

        reader.readAsBinaryString(file);
    } else {
        alert('Please choose an Excel file.');
    }
});

/**
 * ----------------------------- script for export-buttons-------------------------------------------------------------------
 */

$(document).ready(function () {

    //Get today's date in YYYY-MM-DD format
    const today = new Date().toISOString().split('T')[0];
    // Set the default value of the date input to today's date
    // document.getElementById('leaveDate').value = today;

    // Initialize the DataTable
    $('#dataTable').DataTable();

    // loadLeaveData();

    // Initialize dropdown behavior
    $('#columnVisibility').on('click', function(event) {
        event.preventDefault();
        const $dropdownMenu = $(this).next('.dropdown-menu');
        $('.dropdown-menu').not($dropdownMenu).hide();
        $dropdownMenu.toggle();
    });

    // Close dropdown when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.dropdown').length) {
            $('.dropdown-menu').hide();
        }
    });

    // Handle column visibility when the checkbox state changes
    $(document).on('change', '.column-toggle', function () {
        updateColumnVisibility();
    });

    // Initial column visibility update
    updateColumnVisibility();

    // Function to copy visible table data
    $("#copy").click(function () {
        const table = document.getElementById("dataTable");
        const rows = table.querySelectorAll("tr");
        let textToCopy = "";

        // Get headers for copying
        const headers = [];
        table.querySelectorAll("thead th").forEach((header) => {
            const headerText = header.innerText.trim();
            if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(header).is(':visible')) {
                headers.push(headerText);
            }
        });
        textToCopy += headers.join("\t") + "\n";

        // Get data
        rows.forEach(row => {
            const cols = row.querySelectorAll("td, th");

            cols.forEach((col) => {
                const headerText = table.querySelectorAll("th")[col.cellIndex].innerText.trim();

                // Exclude the 'Status' column and check for visibility
                if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(col).is(':visible')) {
                    textToCopy += col.innerText.trim() + "\t";
                }
            });
            textToCopy += "\n";
        });

        navigator.clipboard.writeText(textToCopy.trim());
        alert("Table data copied to clipboard!");
    });

    // Function to export visible table data as CSV
    $("#export-csv").click(function () {
        let csv = [];
        const rows = document.querySelectorAll("#dataTable tr");

        // Get headers for CSV
        const headers = [];
        document.querySelectorAll("#dataTable thead th").forEach((header) => {
            const headerText = header.innerText.trim();
            if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(header).is(':visible')) {
                headers.push(headerText);
            }
        });
        csv.push(headers.join(","));

        // Get data
        rows.forEach(row => {
            const cols = row.querySelectorAll("td, th");
            const csvRow = [];
            cols.forEach((col) => {
                const headerText = document.querySelectorAll("#dataTable th")[col.cellIndex].innerText.trim();

                // Exclude the 'Status' column and check for visibility
                if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(col).is(':visible')) {
                    csvRow.push(col.innerText.replace(/,/g, " "));
                }
            });
            if (csvRow.length > 0) {
                csv.push(csvRow.join(","));
            }
        });

        const csvString = csv.join("\n");
        const blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.setAttribute("download", "EmployeeLeavedata.csv");
        link.click();
    });

    // Function to export visible table data as PDF
    $("#export-pdf").click(function () {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF({ orientation: 'landscape' });
        const table = document.getElementById("dataTable");
        const headers = [];
        const data = [];

        // Get headers from the table
        const headerCols = table.querySelectorAll("thead th");
        headerCols.forEach((header) => {
            const headerText = header.innerText.trim();
            // Exclude the 'Status' column and check for visibility
            if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(header).is(':visible')) {
                headers.push(headerText);
            }
        });

        // Get data from the table rows
        const rows = table.querySelectorAll("tbody tr");
        rows.forEach(row => {
            const rowData = [];
            const cols = row.querySelectorAll("td");
            cols.forEach((col) => {
                const headerText = table.querySelectorAll("thead th")[col.cellIndex].innerText.trim();

                // Exclude the 'Status' column by comparing header text and check for visibility
                if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(col).is(':visible')) {
                    rowData.push(col.innerText);
                }
            });
            if (rowData.length > 0) {
                data.push(rowData);
            }
        });

        // Generate the PDF using autoTable plugin
        doc.autoTable({
            head: [headers],
            body: data,
            theme: 'grid',
            styles: { fontSize: 10 }
        });

        // Save the PDF
        doc.save('EmployeeLeaveData.pdf');
    });

    // Function to export visible table data as Excel
    $("#export-excel").click(function () {
        const table = document.getElementById("dataTable");
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet([]);

        // Get headers from the table, excluding the 'Status' column
        const headerRow = [];
        const headerCells = table.querySelectorAll("thead th");
        headerCells.forEach((headerCell) => {
            const headerText = headerCell.innerText.trim();
            // Exclude the 'Status' column and check for visibility
            if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(headerCell).is(':visible')) {
                headerRow.push(headerText);
            }
        });
        XLSX.utils.sheet_add_aoa(ws, [headerRow], { origin: "A1" });

        // Get data from the table rows, excluding the 'Status' column
        const rows = table.querySelectorAll("tbody tr");
        rows.forEach((row, rowIndex) => {
            const rowData = [];
            const cols = row.querySelectorAll("td");
            cols.forEach((col) => {
                const headerText = table.querySelectorAll("thead th")[col.cellIndex].innerText.trim();

                // Exclude the 'Status' column by comparing header text and check for visibility
                if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(col).is(':visible')) {
                    rowData.push(col.innerText);
                }
            });
            if (rowData.length > 0) { // Add only if the row has data
                XLSX.utils.sheet_add_aoa(ws, [rowData], { origin: `A${rowIndex + 2}` });
            }
        });

        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
        XLSX.writeFile(wb, "EmployeeLeaveData.xlsx"); // Set the default filename
    });

    // Function to print the visible table data
    $("#print").click(function () {
        const table = document.getElementById("dataTable");
        const newWindow = window.open("");
        newWindow.document.write("<html><head><title>Print</title></head><body>");
        newWindow.document.write("<table border='1' style='border-collapse: collapse;'>");

        // Get headers for print
        newWindow.document.write("<tr>");
        table.querySelectorAll("thead th").forEach(header => {
            const headerText = header.innerText.trim();
            // Exclude the 'Status' column and check for visibility
            if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(header).is(':visible')) {
                newWindow.document.write(`<th>${headerText}</th>`);
            }
        });
        newWindow.document.write("</tr>");

        // Get data
        const rows = table.querySelectorAll("tbody tr");
        rows.forEach(row => {
            newWindow.document.write("<tr>");
            const cols = row.querySelectorAll("td");
            cols.forEach((col) => {
                const headerText = table.querySelectorAll("thead th")[col.cellIndex].innerText.trim();

                // Exclude the 'Status' column by comparing header text and check for visibility
                if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(col).is(':visible')) {
                    newWindow.document.write(`<td>${col.innerText}</td>`);
                }
            });
            newWindow.document.write("</tr>");
        });

        newWindow.document.write("</table>");
        newWindow.document.write("</body></html>");
        newWindow.document.close();
        newWindow.print();
    });
    
    // Initialize the dropdown on page load
    populateEmployeeNameDropdown();
});

// Function to update column visibility based on checkbox state
function updateColumnVisibility() {
    $(".column-toggle").each(function () {
        const columnIndex = $(this).val();
        const isChecked = $(this).is(":checked");
        const table = $("#dataTable");

        // Show or hide the column based on checkbox state
        table.find(`tr`).each(function () {
            $(this).find(`td:eq(${columnIndex}), th:eq(${columnIndex})`).css('display', isChecked ? '' : 'none');
        });
    });
}

/**
 * ----------------------------- script for -------------------------------------------------------------------
 */

// Load employees on page load
document.addEventListener('DOMContentLoaded', loadLeaveData);
// Function to load leave data from local storage
function loadLeaveData() {
    const leaves = JSON.parse(localStorage.getItem('employeesLeaveData')) || [];
    const tableBody = document.querySelector('#dataTable tbody');

    // Clear the table
    tableBody.innerHTML = '';

    // Populate the table with leave data
    leaves.forEach((leave, index) => {
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
            <td>${leave.employeeName}</td>
            <td>${leave.employeeId}</td>
            <td>${leave.department}</td>
            <td>${leave.leaveType}</td>
            <td>${convertDateToddmmyyyy(leave.leaveFrom)}</td>
            <td>${convertDateToddmmyyyy(leave.leaveTo)}</td>
            <td>${leave.numberOfDays}</td>
            <td>${leave.durationType}</td>
            <td>${leave.status}</td>
            <td>${leave.reasonForLeave}</td>
            <td>${convertDateToddmmyyyy(leave.requestedOn)}</td>
            <td>${leave.approvedBy || '-'}</td>
            <td>${convertDateToddmmyyyy(leave.approvalDate) || '-'}</td>
            <td>
                <div class="row">
                    <button class="emp-action-btn emp-action-edit" data-index="${index}">
                        <span class="icon" title="Edit"><i class="fas fa-pencil-alt"></i></span>
                    </button>
                    <button class="emp-action-btn emp-action-delete" data-index="${index}">
                        <span class="icon" title="Delete"><i class="fas fa-trash-alt"></i></span>
                    </button>
                </div>
            </td>
        `;
        tableBody.appendChild(newRow);
    });

    // Reinitialize DataTable if using jQuery DataTable
    if ($.fn.DataTable.isDataTable("#dataTable")) {
        $('#dataTable').DataTable().destroy();
    }
    $('#dataTable').DataTable({
        responsive: true,
        autoWidth: false,
        order: [], // Prevent default sorting
    });

    // Attach event listeners to Edit & Delete buttons
    document.querySelectorAll('.emp-action-edit').forEach(btn =>
        btn.addEventListener('click', handleEditLeave)
    );
    document.querySelectorAll('.emp-action-delete').forEach(btn =>
        btn.addEventListener('click', handleDeleteLeave)
    );
}

//--------------------------------------------------------------------------------------------------
// Get references to the Employee Name dropdown and Employee ID field
const employeeNameDropdown = document.getElementById('leaveEmployeeName');
const employeeIdField = document.getElementById('leaveEmployeeId');

// Retrieve employeesData from local storage
const employeesData = JSON.parse(localStorage.getItem('employeesData')) || [];

// Populate Employee Name dropdown on page load
function populateEmployeeNameDropdown() {
    // Clear existing options
    employeeNameDropdown.innerHTML = '<option value="">Select Employee Name</option>';

    // Add options dynamically from employeesData
    employeesData.forEach(employee => {
        const option = document.createElement('option');
        option.value = employee.employeeName;
        option.textContent = employee.employeeName;
        employeeNameDropdown.appendChild(option);
    });
}

// Event listener to update Employee ID field when Employee Name is selected
employeeNameDropdown.addEventListener('change', function () {
    const selectedName = employeeNameDropdown.value;
    const selectedEmployee = employeesData.find(emp => emp.employeeName === selectedName);

    if (selectedEmployee) {
        // Populate the Employee ID field
        employeeIdField.value = selectedEmployee.employeeId1;
    } else {
        // Clear Employee ID field if no match found
        employeeIdField.value = '';
    }
});

//--------------------------------------------------------------------------------------------------
// Event listener for adding a new employee
document.getElementById('leaveEmployerForm').addEventListener('submit', function (event) {
    event.preventDefault();

    saveEmployeeLeave();

    // Clear the form and hide the popup
    document.getElementById('leaveEmployerForm').reset();
    document.getElementById('shift-employer-popup-overlay').style.display = 'none';
});

function saveEmployeeLeave() {
    const employeeId = document.getElementById("leaveEmployeeId").value;
    const employeeName = document.getElementById("leaveEmployeeName").value;
    const department = document.getElementById("department").value;
    const leaveType = document.getElementById("leaveType").value;
    const leaveFrom = document.getElementById("leaveFrom").value;
    const leaveTo = document.getElementById("leaveTo").value;
    const numberOfDays = document.getElementById("numberOfDays").value;
    const durationType = document.getElementById("durationType").value;
    const status = document.getElementById("status").value;
    const reasonForLeave = document.getElementById("reasonForLeave").value;

    // Validate required fields
    if (!employeeId || !employeeName || !leaveFrom || !leaveTo || !numberOfDays || !leaveType || !status || !reasonForLeave) {
        alert("Please fill in all required fields!");
        return;
    }

    // Get current date for 'requestedOn'
    const requestedOn = new Date().toISOString().split('T')[0]; // YYYY-MM-DD

    // Set 'approvedBy' and 'approvalDate' if status is 'Approved'
    let approvedBy = "";
    let approvalDate = "";
    if (status === "Approved") {
        approvedBy = document.getElementById("logged_user").textContent;
        approvalDate = requestedOn; // Use the same date as 'requestedOn'
    }

    // Get the edit index if available
    const saveButton = document.getElementById("employeeLeaveSave");
    const editIndex = saveButton.dataset.editIndex;

    // Get existing leave requests from local storage
    let leaves = JSON.parse(localStorage.getItem("employeesLeaveData")) || [];

    if (editIndex !== undefined && editIndex !== "") {
        const existingLeave = leaves[editIndex];

        // Update the existing leave request
        leaves[editIndex] = {
            ...existingLeave,
            employeeId,
            employeeName,
            department,
            leaveType,
            leaveFrom,
            leaveTo,
            numberOfDays,
            durationType,
            status,
            reasonForLeave,
            approvedBy,
            approvalDate
        };

        alert(`Leave updated successfully! Leave ID: ${existingLeave.leaveId}`);
    } else {
        // Create a new leave request
        const leaveId = `leave-${employeeId}-${Date.now()}`;
        const newLeave = {
            leaveId,
            employeeId,
            employeeName,
            department,
            leaveType,
            leaveFrom,
            leaveTo,
            numberOfDays,
            durationType,
            status,
            reasonForLeave,
            requestedOn,
            approvedBy,
            approvalDate
        };

        leaves.push(newLeave);
        alert(`Leave saved successfully! Leave ID: ${leaveId}`);
    }

    // Save updated leaves to local storage
    localStorage.setItem("employeesLeaveData", JSON.stringify(leaves));

    // Reload the table
    window.location.reload();

    // Clear the form and reset edit mode
    document.getElementById("leaveEmployerForm").reset();
    delete saveButton.dataset.editIndex;
}

// function saveEmployeeLeave() {
//     const employeeId = document.getElementById("leaveEmployeeId").value;
//     const employeeName = document.getElementById("leaveEmployeeName").value;
//     const department = document.getElementById("department").value;
//     const leaveType = document.getElementById("leaveType").value;
//     const leaveFrom = document.getElementById("leaveFrom").value;
//     const leaveTo = document.getElementById("leaveTo").value;
//     const numberOfDays = document.getElementById("numberOfDays").value;
//     const durationType = document.getElementById("durationType").value;
//     const status = document.getElementById("status").value;
//     const reasonForLeave = document.getElementById("reasonForLeave").value;

//     // Validate required fields
//     if (!employeeId || !employeeName || !department || !leaveType || !leaveFrom || !leaveTo || !numberOfDays || !durationType || !status) {
//         alert("Please fill in all the required fields!");
//         return;
//     }

//     // Get current date for 'requestedOn'
//     const requestedOn = new Date().toISOString().split('T')[0]; // YYYY-MM-DD

//     // Set 'approvedBy' and 'approvalDate' if status is 'Approved'
//     let approvedBy = "";
//     let approvalDate = "";
//     if (status === "Approved") {
//         approvedBy = document.getElementById("logged_user").textContent;
//         approvalDate = requestedOn; // Use the same date as 'requestedOn'
//     }

//     // Get save button to check edit mode
//     const saveButton = document.getElementById("employeeLeaveSave");
//     const editIndex = saveButton.dataset.editIndex;

//     // Get existing leaves
//     let leaves = JSON.parse(localStorage.getItem("employeesLeaveData")) || [];

//     if (editIndex !== undefined && editIndex !== "") {
//         const existingLeave = leaves[editIndex];
//         // Updating an existing leave request
//         leaves[editIndex] = {
//             ...leaves[editIndex],
//             employeeId,
//             employeeName,
//             department,
//             leaveType,
//             leaveFrom,
//             leaveTo,
//             numberOfDays,
//             durationType,
//             status,
//             reasonForLeave,
//             requestedOn,
//             approvedBy,
//             approvalDate
//         };

//         alert(`Leave updated successfully! Leave ID: ${existingLeave.leaveId}`);
//     } else {
//         // Creating a new leave request
//         const leaveId = `leave-${employeeId}-${Date.now()}`;

//         const newLeave = {
//             leaveId,
//             employeeId,
//             employeeName,
//             department,
//             leaveType,
//             leaveFrom,
//             leaveTo,
//             numberOfDays,
//             durationType,
//             status,
//             reasonForLeave,
//             requestedOn,
//             approvedBy,
//             approvalDate
//         };

//         leaves.push(newLeave);
//         alert(`Leave request saved successfully!`);
//     }

//     // Save to localStorage
//     localStorage.setItem("employeesLeaveData", JSON.stringify(leaves));

//     // Refresh table data
//     displayEmployeeLeaves();

//     // Reset form and clear edit mode
//     document.getElementById("leaveEmployerForm").reset();
//     delete saveButton.dataset.editIndex;
// }

// Function to handle edit button click
function handleEditLeave(event) {
    const index = event.currentTarget.dataset.index;
    const leaves = JSON.parse(localStorage.getItem('employeesLeaveData')) || [];
    const leave = leaves[index];

    // Populate the form with leave data
    document.getElementById("leaveEmployeeId").value = leave.employeeId;
    document.getElementById("leaveEmployeeName").value = leave.employeeName;
    document.getElementById("department").value = leave.department;
    document.getElementById("leaveType").value = leave.leaveType;
    document.getElementById("leaveFrom").value = convertDateToISO(leave.leaveFrom);
    document.getElementById("leaveTo").value = convertDateToISO(leave.leaveTo);
    document.getElementById("numberOfDays").value = leave.numberOfDays;
    document.getElementById("durationType").value = leave.durationType;
    document.getElementById("status").value = leave.status;
    document.getElementById("reasonForLeave").value = leave.reasonForLeave;

    // Set edit mode
    const saveButton = document.getElementById("employeeLeaveSave");
    saveButton.dataset.editIndex = index;

    // Show popup
    document.getElementById("shift-employer-popup-overlay").style.display = "block";
}
function handleDeleteLeave(event) {
    const index = event.currentTarget.dataset.index;
    if (confirm("Are you sure you want to delete this leave request?")) {
        let leaves = JSON.parse(localStorage.getItem("employeesLeaveData")) || [];
        leaves.splice(index, 1);
        localStorage.setItem("employeesLeaveData", JSON.stringify(leaves));
        window.location.reload();
    }
}
// Function to merge new leave data while avoiding duplicates
function mergeLeaveData(existingData, newData) {
    newData.forEach(newLeave => {
        const existingIndex = existingData.findIndex(leave =>
            leave.employeeId === newLeave.employeeId &&
            leave.leaveFrom === newLeave.leaveFrom &&
            leave.leaveTo === newLeave.leaveTo
        );

        if (existingIndex !== -1) {
            // Replace existing leave data with the new one
            existingData[existingIndex] = newLeave;
        } else {
            // Add new leave data
            existingData.push(newLeave);
        }
    });
    return existingData;
}
// Function to convert Excel numeric date to JavaScript Date
function excelDateToJSDate(excelDate) {
    if (!excelDate) return '';
    const parsedDate = new Date((excelDate - 25569) * 86400 * 1000);
    const day = String(parsedDate.getDate()).padStart(2, '0');
    const month = String(parsedDate.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
    const year = parsedDate.getFullYear();
    return `${day}-${month}-${year}`;
}
// Utility function to convert DD-MM-YYYY to YYYY-MM-DD
function convertDateToISO(dateString) {
    if (!dateString) return ''; // Return empty string for invalid or empty date
    const [day, month, year] = dateString.split('-');
    return `${year}-${month}-${day}`;
}
// Utility function to convert DD-MM-YYYY to YYYY-MM-DD
function convertDateToddmmyyyy(dateString) {
    if (!dateString) return ''; // Return empty string for invalid or empty date
    const [year, month, day] = dateString.split('-');
    return `${day}-${month}-${year}`;
}