document.getElementById('dataTable').addEventListener('click', function(event) {
    if (event.target && event.target.classList.contains('po-btn')) {
        const quotationId = event.target.closest('button').dataset.id; // Assuming first cell has the Quotation ID

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

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

document.getElementById('dataTable').addEventListener('click', function(event) {
    if (event.target && event.target.classList.contains('so-btn')) {
        const quotationId = event.target.closest('button').dataset.id; // Assuming first cell has the Quotation ID

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

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

// Use event delegation for the edit buttons
document.getElementById('dataTable').addEventListener('click', function(event) {
    if (event.target && event.target.classList.contains('edit-btn')) {
        const quotationId = event.target.closest('button').dataset.id; // Assuming first cell has the Quotation ID

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

        // Redirect to the form page for editing details
        window.location.href = 'quotation.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 === 'quotation-pdf') {
        const pdfUrl = event.target.dataset.pdfUrl; // Get the PDF URL from the button's data attribute

        if (pdfUrl) {
            // Open the PDF in a new tab
            window.open(pdfUrl, '_blank');
        } 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', async function () {
    let fileInput = document.getElementById('excelFile');
    let file = fileInput.files[0];

    if (file) {
        let reader = new FileReader();
        
        reader.onload = async 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);

            // Fetch existing quotations from the API
            let existingCompanies = [];
            try {
                const response = await fetch('/api/v1/customers');
                if (!response.ok) {
                    throw new Error(`Failed to fetch existing quotations: ${response.statusText}`);
                }
                existingCompanies = await response.json();
            } catch (error) {
                console.error("Error fetching existing quotation data:", error);
            }

            for (const row of excelData) {
                const quotationId = generateQuotationId();
                const company = row['Company Name']?.trim();
                if (!company) continue;

                // Check if quotation already exists
                let existingComp = existingCompanies.find(q => q.companyName.trim() === company);

                let quotationData = {
                    quotationId: quotationId,
                    quotationDate: row['Quotation Date'] || '',
                    customerReferenceNo: row['Customer Reference No.'] || '',
                    companyName: row['Company Name'] || '',
                    companyEmail: row['Company Email'] || '',
                    companyContactNo: row['Company Contact No.'] || '',
                    gstNo: row['GST No.'] || '',
                    address: row['Address'] || '',
                    productType: row['Product Type'] || '',
                    note: row['Note'] || '',
                    totalAmount: row['Total Amount'] || '',
                };

                // If quotation exists, update it; otherwise, create a new entry
                try {
                    if(!existingComp){
                        let apiUrl ='/api/v1/quotations/';

                        const method = 'POST';

                        const response = await fetch(apiUrl, {
                            method: method,
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(quotationData),
                        });

                        if (!response.ok) {
                            throw new Error(`Failed to ${existingQuotation ? 'update' : 'create'} quotation: ${response.statusText}`);
                        }

                        const responseData = await response.json();
                        console.log(`Quotation ${existingQuotation ? 'updated' : 'created'} successfully:`, responseData);
                    }else{
                        alert(existingComp + " don't exists. Please try after adding company.")
                    }
                } catch (error) {
                    console.error(`Error ${existingQuotation ? 'updating' : 'creating'} quotation:`, error);
                }
            }

            // Reload the quotation list (you can modify this function as needed)
            loadQuotations();

            $('#importModal').modal('hide');
            alert("Quotation details imported successfully!");
        };

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

// Load data from localStorage when the page is loaded

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

$(document).ready(async function () {

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

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

    // 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) => {
            const headerText = header.innerText.trim(); // Defined inside loop
            if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View PDF' && $(header).is(':visible')) {
                headers.push(headerText);
            }
        });
        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 'Image', 'Status' and 'View PDF' columns and check for visibility
                if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View PDF' && $(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(); // Defined inside loop
            if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View PDF' && $(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();

                // Exclude the 'Image', 'Status', 'View PDF' columns and check for visibility
                if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View PDF' && $(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", "data.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(); // Defined inside loop
            if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View PDF' && $(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 'Image', 'Status', 'View PDF' columns and check for visibility
                if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View PDF' && $(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('QuotationData.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(); // Defined inside loop
            if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View PDF' && $(headerCell).is(':visible')) {
                headerRow.push(headerText); // Include only relevant headers
            }
        });
        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', 'Status', 'View PDF' columns and check for visibility
                if (headerText !== 'Image' && headerText !== 'Status' && headerText !== 'View PDF' && $(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, "Quotationdata.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 PDF' && $(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 PDF' && $(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();
    });
});


// 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 -------------------------------------------------------------------
 */
// Function to generate the quotationNo ID
async function generateQuotationId() {
    try {
        const response = await fetch('/api/v1/quotations/');
        if (!response.ok) {
            throw new Error(`Failed to fetch quotation data: ${response.statusText}`);
        }
        const quotationDataList = await response.json();

        // Extract the numeric portions of all Quotation IDs
        const allIds = quotationDataList.map(data => {
            const idParts = data.quotationNo1?.split('/');
            return idParts && idParts.length === 3 ? parseInt(idParts[2], 10) : 0;
        });

        // Find the largest numeric portion
        const maxIdNumber = Math.max(0, ...allIds);

        // Generate the new ID based on the largest number + 1
        const newIdNumber = (maxIdNumber + 1).toString().padStart(4, '0');

        // Construct and return the new Quotation ID
        return `UEPL/QT/${newIdNumber}`;
    } catch (error) {
        console.error("Error generating Quotation ID:", error);
        return null;
    }
}

// This is your loadQuotations function (you need to implement this if it's not already done)
async function loadQuotations() {
    try {
        const response = await fetch('/api/v1/quotations/');
        if (!response.ok) {
            throw new Error(`Failed to load quotations: ${response.statusText}`);
        }
        const quotations = await response.json();

        const response1 = await fetch('/api/v1/customers');
        if (!response1.ok) {
            throw new Error(`Failed to load customers: ${response1.statusText}`);
        }
        const companyData = await response1.json();
        let table = $('#dataTable').DataTable();

        // Populate table with saved data
        quotations.forEach((item) => {
            const dateParts = item.quotationDate.split("-");
            const formattedDate = `${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`;

            const companyEntry = companyData.find(company => company.companyName === item.companyName);
            let convertColumnContent = '';

            // Check the companyId1 value and add buttons accordingly
            if (companyEntry && companyEntry.companyId1) {
                const companyId1 = companyEntry.companyId1;

                if (companyId1.includes('UEPL/CUS/')) {
                    convertColumnContent = `<button class="btn btn-warning so-btn convert-btn" data-id="${item.id}">SO</button>`;
                } else if (companyId1.includes('UEPL/VEN/')) {
                    convertColumnContent = `<button class="btn btn-info po-btn convert-btn" data-id="${item.id}">PO</button>`;
                } else if (companyId1.includes('UEPL/CV/')) {
                    convertColumnContent = `
                        <button class="btn btn-info po-btn convert-btn" data-id="${item.id}">PO</button>
                        <button class="btn btn-warning so-btn convert-btn" data-id="${item.id}">SO</button>
                    `;
                }
            }

            // Append the data to the DataTable
            table.row.add([
                item.quotationNo1 || '',
                formattedDate || '',
                item.custRefNo || '',
                item.companyName || '',
                item.companyEmail || '',
                item.companyPhone || '',
                item.gstNo || '',
                item.address || '',
                item.productType || '',
                item.quoteNote || '',
                item.grandTotal || '',
                `<button class="btn btn-danger edit-btn" data-id="${item.id}">Edit</button>`,
                `<button id="quotation-pdf" class="btn btn-success" data-pdf-url="${item.pdfFileUrl || ''}">View</button>`,
                convertColumnContent
            ]).draw(false);
        });    
    } catch (error) {
        console.error("Error loading quotations:", error);
    }
}