/**
 * ----------------------------- script for edit button-------------------------------------------------------------------
 */

// Use event delegation for the edit buttons
document.getElementById('dataTable').addEventListener('click', function(event) {
    if (event.target && event.target.classList.contains('edit-btn')) {
        const row = event.target.closest('tr');
        const invoiceId = row.cells[0].innerText; // Assuming first cell has the Quotation ID

        // Store the quotation ID in session storage
        sessionStorage.setItem('currentInvoiceId', invoiceId);

        // Redirect to the form page for editing details
        window.location.href = 'tax-invoice.html';
    }
});

/**
 * ----------------------------- 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 === 'Inv-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() {
    let fileInput = document.getElementById('excelFile');
    let file = fileInput.files[0]; // Get the uploaded file

    if (file) {
        let reader = new FileReader();
        
        // Read the file as a binary string
        reader.onload = function(e) {
            let data = e.target.result;
            let workbook = XLSX.read(data, { type: 'binary' });
            
            // Assuming the first sheet contains the data
            let sheetName = workbook.SheetNames[0];
            let sheet = workbook.Sheets[sheetName];
            
            // Convert sheet to JSON format
            let excelData = XLSX.utils.sheet_to_json(sheet);
            
            // Process the data and add it to the table
            appendExcelDataToInvoiceTable(excelData);

            // Store the data in localStorage
            localStorage.setItem('excelInvoiceData', JSON.stringify(excelData));

            // Close the modal
            $('#importModal').modal('hide');
            alert("Invoice details imported successfully!");
        };

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

// Function to append Excel data to the invoice table
function appendExcelDataToInvoiceTable(excelData) {
    let invoiceTable = $('#dataTable').DataTable();

    excelData.forEach(function(rowData) {
        // Append the data to the DataTable
        invoiceTable.row.add([
            rowData['Invoice ID'] || '',
            rowData['Invoice Date'] || '',
            // rowData['IRN No'] || '',
            // rowData['ACK No'] || '',
            // rowData['ACK Date'] || '',
            // `<canvas class="textCanvas" width="50" height="50" style="display: none;"></canvas>
            //  <img class="generated-image" src="" alt="Initials Image">`,
            rowData['Company Name'] || '',
            rowData['Company Email'] || '',
            rowData['Company Contact No.'] || '',
            rowData['GST No.'] || '',
            rowData['Reference No'] || '',
            rowData['Reference Date'] || '',
            rowData['Buyers Order No'] || '',
            rowData['Destination'] || '',
            rowData['Vehicle No'] || '',
            rowData['Total Amount'] || '',
            rowData['Total Tax Amount'] || '',
            `<button class="btn btn-danger edit-btn" type="button">Edit</button>`,
            `<button class="btn btn-success view-btn" type="button">View</button>`
        ]).draw(false); // Use draw(false) to prevent a full redraw
    });
}




// Load data from localStorage when the page is loaded

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

$(document).ready(function () {

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

    // let storedData = localStorage.getItem('excelInvoiceData');
    
    // if (storedData) {
    //     // Parse the JSON data and append it to the table
    //     let excelData = JSON.parse(storedData);
    //     appendExcelDataToInvoiceTable(excelData);
    // }


    // Retrieve saved invoice data from local storage
    const savedInvoices = JSON.parse(localStorage.getItem('InvoiceDataList')) || [];
    let invoiceTable = $('#dataTable').DataTable();

    // Populate table with saved data
    savedInvoices.forEach((invoice) => {
        // Format the dates as dd-mm-yyyy
        const invoiceDate = invoice.invoiceDate ? new Date(invoice.invoiceDate).toLocaleDateString('en-GB') : '';
        const ackDate = invoice.ackDate ? new Date(invoice.ackDate).toLocaleDateString('en-GB') : '';
        const referenceDate = invoice.referenceDate ? new Date(invoice.referenceDate).toLocaleDateString('en-GB') : '';

        // Append the data to the DataTable
        invoiceTable.row.add([
            invoice.invoiceNo1 || '', // Invoice ID
            invoiceDate || '', // Invoice Date
            // invoice.irnNo || '', // IRN No
            // invoice.ackNo || '', // ACK No
            // ackDate || '', // ACK Date
            // `<canvas class="textCanvas" width="50" height="50" style="display: none;"></canvas>
            // <img class="generated-image" src="" alt="Initials Image">`, // Image placeholder
            invoice.companyName || '', // Company Name
            invoice.companyEmail || '', // Company Email
            invoice.companyPhone || '', // Company Contact No.
            invoice.companyGst || '', // GST No.
            invoice.referenceNo || '', // Reference No
            referenceDate || '', // Reference Date
            invoice.buyersOrderNo || '', // Buyers Order No
            invoice.destination || '', // Destination
            invoice.vehicleNo || '', // Vehicle No
            invoice.grandTotal || '', // Total Amount
            invoice.totalTax || '', // Total Tax Amount
            `<button class="btn btn-danger edit-btn" type="button">Edit</button>`,
            `<button id="Inv-pdf" class="btn btn-success" data-pdf-url="${invoice.pdfDataUrl || ''}">View</button>` // View Details
        ]).draw(false); // Use draw(false) to prevent a full redraw
    });



    

    // Initialize dropdown behavior
    $('#columnVisibility').on('click', function(event) {
        event.preventDefault(); // Prevent default action
        const $dropdownMenu = $(this).next('.dropdown-menu'); // Target the specific dropdown menu
        $('.dropdown-menu').not($dropdownMenu).hide(); // Hide other dropdowns
        $dropdownMenu.toggle(); // Toggle the associated dropdown menu
    });

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

    // 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) => {
            if ($(header).is(':visible') && header.innerText.trim() !== 'Status' && header.innerText.trim() !== 'View Details') {
                headers.push(header.innerText.trim());
            }
        });
        textToCopy += headers.join("\t") + "\n"; // Add headers

        // 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 !== 'Status' && headerText !== 'View Details' && $(col).is(':visible')) {
                    textToCopy += col.innerText.trim() + "\t"; // Add a tab between columns
                }
            });
            textToCopy += "\n"; // New line after each row
        });

        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) => {
            if ($(header).is(':visible') && header.innerText.trim() !== 'Status' && header.innerText.trim() !== 'View Details') {
                headers.push(header.innerText.trim());
            }
        });
        csv.push(headers.join(",")); // Add header row

        // 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 !== 'Status' && headerText !== 'View Details' && $(col).is(':visible')) {
                    csvRow.push(col.innerText.replace(/,/g, " ")); // Replace commas to avoid issues
                }
            });
            if (csvRow.length > 0) { // Add only if the row has data
                csv.push(csvRow.join(",")); // Join the row values with a comma
            }
        });

        const csvString = csv.join("\n"); // Join rows with a new line
        const blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.setAttribute("download", "InvoiceData.csv"); // Set the default filename
        link.click(); // Trigger the download
    });

    // Function to export visible table data as PDF 
    $("#export-pdf").click(function () {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF({ orientation: 'landscape' }); // Set orientation to 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 !== 'Status' && 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 !== 'Status' && headerText !== 'View Details' && $(col).is(':visible')) {
                    rowData.push(col.innerText);
                }
            });
            if (rowData.length > 0) { // Add only if the row has data
                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('InvoiceData.pdf');
    });

    // Function to export visible table data as Excel
    $("#export-excel").click(function () {
        const table = document.getElementById("dataTable");
        const wb = XLSX.utils.book_new(); // Create a new Excel workbook
        const ws = XLSX.utils.aoa_to_sheet([]); // Create an empty 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 'Image', 'Status', and 'View Details' columns and check for visibility using jQuery
            if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View Details' && $(headerCell).is(':visible')) {
                headerRow.push(headerText); // Include only relevant headers
            }
        });

        // Add the headers to the sheet
        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, colIndex) => {
                const headerText = table.querySelectorAll("thead th")[colIndex].innerText.trim();

                // Exclude the 'Image', 'Status', and 'View Details' columns and check for visibility of each column
                if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View Details' && $(col).is(':visible')) {
                    rowData.push(col.innerText.trim()); // Add the data of the visible cells
                }
            });

            // Only add non-empty rows
            if (rowData.length > 0) {
                XLSX.utils.sheet_add_aoa(ws, [rowData], { origin: `A${rowIndex + 2}` });
            }
        });

        // Append the sheet to the workbook
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        // Write the workbook to a file
        XLSX.writeFile(wb, "Invoicedata.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 !== 'Status' && 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 !== 'Status' && 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();
    });


    



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

    // Array of background colors to cycle through
    const backgroundColors = ['#95b4e6','#95e6cd', '#95e69f', '#b5c979', '#d795e6', '#e69595'];
    let colorNo = 0; // To keep track of the current color

    function getInitialsFromName(name) {
        const words = name.trim().split(' ');
        const initials = words.map(word => word[0].toUpperCase()).join('');
        return initials;
    }

    function generateImageWithInitials(initials, backgroundColor, canvas) {
        const context = canvas.getContext('2d');

        // Set background color
        context.fillStyle = backgroundColor;
        context.fillRect(0, 0, canvas.width, canvas.height);

        // Set text properties
        context.font = '15px Arial';
        context.fillStyle = '#FFFFFF'; // Text color (white)
        context.textAlign = 'center';
        context.textBaseline = 'middle';

        // Draw the initials on the canvas
        context.fillText(initials, canvas.width / 2, canvas.height / 2);

        // Convert the canvas content to a data URL and return it
        return canvas.toDataURL('image/png');
    }

    function generateImagesForTable() {
        // Get all rows in the table body
        const rows = document.querySelectorAll('#dataTable tbody tr');

        rows.forEach(row => {
            // Get the company name from the table row (third cell, index 2)
            const companyName = row.cells[6].textContent;
            const initials = getInitialsFromName(companyName);

            // Get the canvas and image elements from the table cell
            const canvas = row.querySelector('.textCanvas');
            const imageElement = row.querySelector('.generated-image');

            // Get the next background color from the array
            const backgroundColor = backgroundColors[colorNo];
            colorNo = (colorNo + 1) % backgroundColors.length; // Move to the next color

            // Generate the image with the initials and background color
            const imageDataUrl = generateImageWithInitials(initials, backgroundColor, canvas);

            // Display the generated image
            if (imageElement) {
                imageElement.src = imageDataUrl;
            }
        });
    }


    // Function to initialize the MutationObserver
    function observeTableChanges() {
        const tableBody = document.querySelector('#dataTable tbody');

        if (tableBody) {
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (mutation.type === 'childList') {
                        generateImagesForTable(); // Call the function to regenerate images
                    }
                });
            });

            // Configuration of the observer
            const config = { childList: true, subtree: true };
            observer.observe(tableBody, config);
        }
    }

    // Call the function to observe table changes when the page loads
    window.onload = function () {
        generateImagesForTable();
        observeTableChanges(); // Start observing table content changes
    };

    
});


// 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"); // Ensure this ID matches your actual table ID

        // 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 -------------------------------------------------------------------
 */

