/**
 * ----------------------------- 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 grnId1 = row.cells[0].innerText; 

        sessionStorage.setItem('currentgrnId', grnId1);

        // Redirect to the form page for editing details
        window.location.href = 'grn-form.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 === 'challan-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
            appendExcelDataToTable(excelData);

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

            // Close the modal
            $('#importModal').modal('hide');
            alert("GRN details imported successfully!");
        };
        reader.readAsBinaryString(file);
    } else {
        alert("Please choose an Excel file.");
    }
});

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

    // Instead of clearing the table, just append the new data
    excelData.forEach(function(rowData) {
        // Append the data to the DataTable
        table.row.add([
            rowData['GRN ID'] || '',
            rowData['GRN Date'] || '',
            rowData['Order ID'] || '',
            rowData['Order Date'] || '',
            rowData['Order Referece No'] || '',
            rowData['Quotation ID'] || '',
            rowData['RFQ ID'] || '',
            rowData['Company Name'] || '',
            rowData['Company Email'] || '',
            rowData['Phone Number'] || '',
            rowData['Company Address'] || '',
            rowData['GST'] || '',
            rowData['Part No'] || '',
            rowData['Project Material No'] || '',
            rowData['Drawing ID'] || '',
            rowData['Drawing Revision'] || '',
            `<button id="challan-pdf" class="btn btn-success">View</button>`,
            rowData['Description'] || '',
            rowData['Product Type'] || '',
            `<button class="btn btn-danger edit-btn" type="button">Edit</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('excelGRNData');
    
    // if (storedData) {
    //     // Parse the JSON data and append it to the table
    //     let excelData = JSON.parse(storedData);
    //     appendExcelDataToTable(excelData);
    // }

    // Retrieve saved grn data from local storage
    const savedgrnData = JSON.parse(localStorage.getItem('grnDataList')) || [];
    let grnTable = $('#dataTable').DataTable();

    savedgrnData.forEach((grn) => {
        grnTable.row.add([
            grn.grnNo1 || '',
            grn.grnDate1 || '',
            grn.orderNo || '',
            grn.orderDate || '',
            grn.orderRefNo || '',
            grn.quotationNo || '',
            grn.rfqNo || '',
            grn.companyName || '',
            grn.companyEmail || '',
            grn.companyPhone || '',
            grn.companyAddress || '',
            grn.companyGSTN || '',
            grn.partNo || '',
            grn.projectMaterialNo || '',
            grn.drawingNo || '',
            grn.drawingRev || '',
            `<button id="challan-pdf" class="btn btn-success" data-pdf-url="${grn.challan}" >View</button>`,
            grn.description || '',
            grn.productType || '',
            `<button class="btn btn-danger edit-btn">Edit</button>`
        ]).draw(false);
    });
    // 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() !== 'Image') {
                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 !== 'Image' && headerText !== 'Status' && $(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) => {
            const headerText = header.innerText.trim(); // Get the text of the header
            if (headerText !== 'Image' && headerText !== 'Status' && $(header).is(':visible')) {
                headers.push(headerText);
            }
        });
        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(); // Get header text of the current column

                // Exclude the 'Status' column and check for visibility
                if (headerText !== 'Image' && headerText !== 'Status' && $(col).is(':visible')) {
                    csvRow.push(col.innerText.replace(/,/g, " ")); // Replace commas with spaces to avoid CSV 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", "grnData.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' && $(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' && $(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('grnData.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([]); // Create 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 'Status' and 'Image' columns and check for visibility
            if ((headerText !== 'Status' && headerText !== 'Image') && $(headerCell).is(':visible')) {
                headerRow.push(headerText); // Include only relevant headers
            }
        });

        // Add header row to Excel sheet
        if (headerRow.length > 0) {
            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 'Image' and 'Status' columns and check for visibility
                if ((headerText !== 'Status' && headerText !== 'Image') && $(col).is(':visible')) {
                    rowData.push(col.innerText.trim());
                }
            });

            if (rowData.length > 0) { // Only add row if data is present
                XLSX.utils.sheet_add_aoa(ws, [rowData], { origin: `A${rowIndex + 2}` });
            }
        });

        // Add sheet to the workbook and trigger download
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
        XLSX.writeFile(wb, "grnData.xlsx"); // Set 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, excluding 'Status' and 'Image' columns
        newWindow.document.write("<tr>");
        table.querySelectorAll("thead th").forEach(header => {
            const headerText = header.innerText.trim();
            // Exclude 'Status' and 'Image' columns and check for visibility
            if (headerText !== 'Status' && headerText !== 'Image' && $(header).is(':visible')) {
                newWindow.document.write(`<th>${headerText}</th>`);
            }
        });
        newWindow.document.write("</tr>");

        // Get data, excluding 'Status' and 'Image' columns
        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 'Status' and 'Image' columns and check for visibility
                if (headerText !== 'Status' && headerText !== 'Image' && $(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();

        // Trigger the print dialog
        newWindow.print();
    });
});


// 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 -------------------------------------------------------------------
 */
// document.addEventListener('DOMContentLoaded', () => {
//     const grnToggleButtons = document.querySelectorAll('.grn-toggle');
//     const pageHeader = document.getElementById('grn-page-header');
//     const tableHeaders = document.querySelector('#dataTable thead tr');
//     const tableFooters = document.querySelector('#dataTable tfoot tr');

//     grnToggleButtons.forEach(radio => {
//         radio.checked = false;
//     });

//     // Retrieve saved grn data from local storage
//     const savedgrnData = JSON.parse(localStorage.getItem('grnDataList')) || [];
//     let grnTable = $('#dataTable').DataTable();

//     // Define headers for Purchase and Sales GRN
//     const purchaseHeaders = [
//         "GRN ID", "GRN Date", "Purchase ID", "Quotation ID", "RFQ ID", 
//         "Vendor Name", "Vendor Email", "Phone Number", "Vendor Address", 
//         "GST", "Part No", "Project Material No", "Drawing ID", 
//         "Description", "Product Type", "Grand Total", "Status"
//     ];

//     const salesHeaders = [
//         "GRN ID", "GRN Date", "Sales ID", "Quotation ID", "RFQ ID", 
//         "Customer Name", "Customer Email", "Phone Number", "Customer Address", 
//         "GST", "Part No", "Project Material No", "Drawing ID", 
//         "Description", "Product Type", "Grand Total", "Status"
//     ];

//     // Update table headers dynamically
//     const updateTableHeaders = (headers) => {
//         tableHeaders.innerHTML = headers.map(header => `<th>${header}</th>`).join('');
//         tableFooters.innerHTML = headers.map(header => `<th>${header}</th>`).join('');
//     };

//     // Event listener for radio buttons
//     grnToggleButtons.forEach(button => {
//         button.addEventListener('change', (event) => {
    
//             if (event.target.checked) {
//                 grnTable.clear().draw();
    
//                 if (event.target.value === '0') {
//                     // pageHeader.textContent = 'Purchase GRN Datatable';
//                     document.getElementById('dataTable').classList.remove('hidden');
//                     updateTableHeaders(purchaseHeaders);
//                     savedgrnData.forEach((grn) => {
//                         if (grn.pOrderNo) {
//                             grnTable.row.add([
//                                 grn.grnNo1 || '',
//                                 grn.grnDate1 || '',
//                                 grn.pOrderNo || '',
//                                 grn.pquotationNo || '',
//                                 grn.prfqNo || '',
//                                 grn.vendorCompanyName || '',
//                                 grn.poCompanyEmail || '',
//                                 grn.poCompanyPhone || '',
//                                 grn.poCompanyAddress || '',
//                                 grn.poCompanyGSTN || '',
//                                 grn.ppartNo || '',
//                                 grn.pprojectMaterialNo || '',
//                                 grn.pdrawingNo || '',
//                                 grn.pdescription || '',
//                                 grn.pproductType || '',
//                                 grn.pgrandTotal || '',
//                                 `<button class="btn btn-danger edit-btn">Edit</button>`
//                             ]).draw(false);
//                         }
//                     });
//                 } else if (event.target.value === '1') {
//                     // pageHeader.textContent = 'Sales GRN Datatable';
//                     document.getElementById('dataTable').classList.remove('hidden');
//                     updateTableHeaders(salesHeaders);
//                     savedgrnData.forEach((grn) => {
//                         if (grn.sOrderNo) {
//                             grnTable.row.add([
//                                 grn.grnNo1 || '',
//                                 grn.grnDate1 || '',
//                                 grn.sOrderNo || '',
//                                 grn.squotationNo || '',
//                                 grn.srfqNo || '',
//                                 grn.customerCompanyName || '',
//                                 grn.soCompanyEmail || '',
//                                 grn.soCompanyPhone || '',
//                                 grn.soCompanyAddress || '',
//                                 grn.soCompanyGSTN || '',
//                                 grn.spartNo || '',
//                                 grn.sprojectMaterialNo || '',
//                                 grn.sdrawingNo || '',
//                                 grn.sdescription || '',
//                                 grn.sproductType || '',
//                                 grn.sgrandTotal || '',
//                                 `<button class="btn btn-danger edit-btn">Edit</button>`
//                             ]).draw(false);
//                         }
//                     });
//                 }
//             }
//         });
//     });    
// });
