let username; // Declare username as a global variable
// Extract machine item number from the URL's parameters
function getMachineItemNoFromURL() {
    let params = new URLSearchParams(window.location.search);
    return params.get('itemNo');
}

let machineItemNo = getMachineItemNoFromURL();

// If machineItemNo exists, then load the relevant machine details and spare parts data
if (machineItemNo) {
    updatePopup(machineItemNo);
    getImagePath(machineItemNo);  // Call the getImagePath function
    getManualPath(machineItemNo);  // Added this line to call the getManualPath function
}

function updatePopup(itemNo) {
    // For now, just updating the displayItemNo element with the passed item number
    document.getElementById('displayItemNo').textContent = itemNo;
    
    // If there are other details you wish to display, this is where you would add that logic.
}

window.addEventListener("message", function(event) {
    // Extract the row data from the event
    let rowData = event.data;

    // Check if the received data is an array and has the expected length
    if (Array.isArray(rowData) && rowData.length === 8) {
        // Extract data from the rowData array
        let [orderNo, customerName, description, serialNo, itemNo, account, date, reciever] = rowData;

        // Display the data in the popup window
        let table = document.getElementById("popup-table");
        let tr = document.createElement("tr");

        // Create a new data row and populate it with the data
        rowData.forEach(cellData => {
            let td = document.createElement("td");
            td.innerText = cellData;
            tr.appendChild(td);
            console.log("Received data in popup:", event.data);
        });

        table.appendChild(tr);
        document.getElementById("displayOB1").innerText = rowData[0];  // Display value from cell no. 1
        document.getElementById("displayCustomer2").innerText = rowData[1];  // Display value from cell no. 2
        document.getElementById("displayDescription3").innerText = rowData[2];  // Display value from cell no. 3
        document.getElementById("displaySerial4").innerText = rowData[3];  // Display value from cell no. 4
        document.getElementById("displayItemNo5").innerText = rowData[4];  // Display value from cell no. 5
        document.getElementById("displayAccount6").innerText = rowData[5];  // Display value from cell no. 6
        document.getElementById("displayWarranty7").innerText = rowData[6];  // Display value from cell no. 7
        document.getElementById("reciever").innerText = rowData[7];  // Display value from cell no. 8
    }
});


// This is for the separator BAR
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        let href = this.getAttribute('href');
        if (href && href !== "#") {
            let targetElement = document.querySelector(href);
            if (targetElement) {
                targetElement.scrollIntoView({ behavior: 'smooth' });
            }
        }
    });
});

// Function to get image path from machinepics.xlsx based on Item no
function getImagePath(itemNo) {
    fetch('machinepics.xlsx').then(response => {
        return response.arrayBuffer();
    }).then(data => {
        let workbook = XLSX.read(data, {type: 'array'});
        let firstSheetName = workbook.SheetNames[0];
        let worksheet = workbook.Sheets[firstSheetName];
        let jsonData = XLSX.utils.sheet_to_json(worksheet);
        console.log("Loaded data:", jsonData);

        // Default image path
        let imagePath = 'https://service.labotek.dk/serviceplatform/img/notavailable.png';

        for (let row of jsonData) {
            console.log("Comparing: ", String(row['Item_No']), " with: ", String(itemNo));
            // Ensuring comparisons as strings
            if (String(row['Item_No']) === String(itemNo)) {
                imagePath = row['image source'];
                console.log("Match found! Image path is: ", imagePath);
                break;
            }
        }

        // Assuming you have an image element in your popup.html with the id 'machineImage'
        let imageElement = document.getElementById('machineImage');
        imageElement.src = imagePath;

    }).catch(error => {
        console.error("Error fetching or processing the Excel file:", error);
    });
}

// Function to get manual path from machinepics.xlsx based on Item no
function getManualPath(itemNo) {
    fetch('machinepics.xlsx').then(response => {
        return response.arrayBuffer();
    }).then(data => {
        let workbook = XLSX.read(data, {type: 'array'});
        let firstSheetName = workbook.SheetNames[0];
        let worksheet = workbook.Sheets[firstSheetName];
        let jsonData = XLSX.utils.sheet_to_json(worksheet);
        console.log("Loaded data:", jsonData);

        // Default manual path
        let manualPath = '/path-to-default-manual.pdf';

        for (let row of jsonData) {
            console.log("Comparing: ", String(row['Item_No']), " with: ", String(itemNo));
            if (String(row['Item_No']) === String(itemNo)) {
                // Only update manualPath if it is not null/undefined in the Excel data
                if (row['manual']) {
                    manualPath = row['manual'];
                    console.log("Match found! Manual path is: ", manualPath);
                }
                break;
            }
        }

        // Assuming you have an anchor element in your popup.html with the id 'manualLink'
        let manualLinkElement = document.getElementById('manualLink');
        manualLinkElement.href = manualPath;

    }).catch(error => {
        console.error("Error fetching or processing the Excel file:", error);
    });
}


// Code for the REPORT BUG function
function gatherPopupData() {
    return {
        orderNo: document.getElementById("displayOB1").innerText.trim(),
        customerName: document.getElementById("displayCustomer2").innerText.trim(),
        description: document.getElementById("displayDescription3").innerText.trim(),
        serialNo: document.getElementById("displaySerial4").innerText.trim(),
        itemNo: document.getElementById("displayItemNo5").innerText.trim(),
        account: document.getElementById("displayAccount6").innerText.trim()
        // warranty is not included in your mapping, so it's omitted
    };
}


// Add an event listener to the 'Report Bug' button
document.getElementById('reportBugButton').addEventListener('click', function() {
    let popupData = gatherPopupData();

    fetch('https://service.labotek.dk/serviceplatform/reportBug.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(popupData)
})
.then(response => {
    if (!response.ok) {
        throw new Error('Network response was not ok');
    }
    return response.json();
})
.then(data => {
    if (data.error) {
        // Handle the error message here, for example, display it to the user
        console.error('Error:', data.error);
        alert('Error: ' + data.error);
    } else {
        // Handle the success case here
        alert('Bug report submitted successfully. Thank you for assisting!');
    }
})
.catch(error => {
    console.error('Error:', error);
    alert('Failed to submit bug report. Please contact Labotek Team');
});
});


// Code for the MODAL

function generateSparePartsPopup(spareParts) {
    const sparePartsList = document.getElementById('sparePartsList');
    sparePartsList.innerHTML = "";  // Clear previous spare parts data
    
    spareParts.forEach(sparePart => {
        const tableRow = document.createElement('tr');

        // Checkbox Cell
        const selectCell = document.createElement('td');
        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        selectCell.appendChild(checkbox);
        tableRow.appendChild(selectCell);

        // Part No Cell
        const partNoCell = document.createElement('td');
        partNoCell.textContent = sparePart['Part no'];
        tableRow.appendChild(partNoCell);

        // Description Cell
        const descriptionCell = document.createElement('td');
        descriptionCell.textContent = sparePart['Description'];
        tableRow.appendChild(descriptionCell);
        
        // QTY Cell with Editable Input
        const qtyCell = document.createElement('td');
        const qtyInput = document.createElement('input');
        qtyInput.type = 'number';
        qtyInput.value = sparePart['Qty'];  // Set the initial value
        qtyInput.className = 'qty-input';
        qtyCell.appendChild(qtyInput);
        tableRow.appendChild(qtyCell);

        // UNITS Cell
        const unitCell = document.createElement('td');
        unitCell.textContent = sparePart['Unit'];
        tableRow.appendChild(unitCell);

        // Stock Cell (New Column)
        const stockCell = document.createElement('td');
        stockCell.textContent = sparePart['Stock'];  // Add the stock value here
        tableRow.appendChild(stockCell);

        sparePartsList.appendChild(tableRow);
    });

    // Show the modal
    document.getElementById('sparePartsModal').style.display = "block";
}

 
// When the user clicks on the link, open the modal and populate it with data
document.getElementById('sparePartsLink').addEventListener('click', async function(e) {
    e.preventDefault();
    const itemNo = getMachineItemNoFromURL();
    console.log("Item No: ", itemNo);  // Debug log
    const allSparePartsData = await getSparePartsData();
    const relatedSpareParts = filterSparePartsByItemNo(allSparePartsData, itemNo);
    generateSparePartsPopup(relatedSpareParts);
});


// When the user clicks on <span> (x), close the modal
document.getElementById('closeModal').addEventListener('click', function() {
    document.getElementById('sparePartsModal').style.display = "none";
});

// When the user clicks anywhere outside of the modal, close it
window.addEventListener('click', function(event) {
    if (event.target === document.getElementById('sparePartsModal')) {
        document.getElementById('sparePartsModal').style.display = "none";
    }
});


// Assuming 'spareparts.xlsx' is in the same directory as your HTML file
async function getSparePartsData() {
    const response = await fetch('spareparts.xlsx');
    const arrayBuffer = await response.arrayBuffer();
    const workbook = XLSX.read(arrayBuffer, {type: 'array'});
    const worksheet = workbook.Sheets['spareparts']; // Use the new sheet
    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    
    console.log("Fetched Spare Parts Data:", jsonData);
    
    // Filter to only include rows where 'sparepart' column is 1
    const filteredData = jsonData.filter(row => row['sparepart'] === 1);
    
    return filteredData;
}

function filterSparePartsByItemNo(sparePartsData, itemNo) {
    return sparePartsData.filter(sparePart => {
        return String(sparePart['Item no']) === String(itemNo);
    });
}


document.getElementById('selectAll').addEventListener('click', function() {
    const checkboxes = document.querySelectorAll('#sparePartsList input[type="checkbox"]');
    const allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);
    checkboxes.forEach(checkbox => checkbox.checked = !allChecked);
});


  // ***************EXPORT TO EXCEL FUNCTION*******************
document.getElementById('exportToExcel').addEventListener('click', function() {
    let table = document.getElementById('sparePartsTable');
    let selectedParts = [['Part No', 'Description','Qty', 'Unit' ]];  // Added headers
    
    for (let i = 1, row; row = table.rows[i]; i++) {
        if (row.cells[0].querySelector('input').checked) {
            let partNo = row.cells[1].textContent;
            let description = row.cells[2].textContent;
            selectedParts.push([partNo, description]);
        }
    }

    if (selectedParts.length > 1) {  // Check if more than just the headers
        // Retrieve order no and serial no from HTML elements
        let orderNo = document.getElementById('displayOB1').innerText;
        let serialNo = document.getElementById('displaySerial4').innerText;
        downloadExcel(selectedParts, orderNo, serialNo);
    } else {
        alert('No parts selected!');
    }
});


//  ***************** Function to generate Excel file *****************
function downloadExcel(data, orderNo, serialNo) {
    return new Promise((resolve, reject) => {
        let ws_name = "SpareParts";
        let wb = XLSX.utils.book_new();
        let ws = XLSX.utils.aoa_to_sheet(data);
        XLSX.utils.book_append_sheet(wb, ws, ws_name);

        // Get today's date and format it as YYYYMMDD
        let today = new Date();
        let formattedDate = today.toISOString().slice(0, 10).replace(/-/g, "");

        // Create filename using order no, serial no, and today's date
        let filename = `sparepartsorder_${orderNo}_${serialNo}_${formattedDate}.xlsx`;

        try {
            let wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
            let blob = new Blob([wbout], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});

            // Create a link element for downloading the file
            let a = document.createElement('a');
            document.body.appendChild(a);
            let url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = filename;
            a.click();
            setTimeout(() => {
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            }, 0);

            resolve({blob, filename});
            console.log("Excel file generated, downloaded, and blob created");
        } catch (error) {
            console.error("Error in generating Excel:", error);
            reject(error);
        }
    });
}

// // **************** ORDER BUTTON EXPORT TO EXCEL FUNCTION Create Workbook & EMAIL// **************** 
// Attach the validation and order processing to the button
document.getElementById('order').addEventListener('click', async function (event) {
    // Validate the request form (Name & Email)
    const name = document.getElementById('userName').value;
    const email = document.getElementById('userEmail').value;
    const errorMessage = document.getElementById('error-message');
    
    // Perform validation before proceeding
    if (!name || !email) {
        errorMessage.innerText = 'Both Name and Email are required!';
        errorMessage.style.display = 'block';
        event.preventDefault(); // Prevent submission if validation fails
        return;
    } else {
        errorMessage.innerText = '';
        errorMessage.style.display = 'none';
    }

    // Continue with the order processing
    let table = document.getElementById('sparePartsTable');
    let selectedParts = [['Part No', 'Description', 'Qty', 'Unit']];  // Added name and email headers
    
    // Loop through the table rows and gather selected parts data
    for (let i = 1, row; row = table.rows[i]; i++) {
        if (row.cells[0].querySelector('input').checked) {
            let partNo = row.cells[1].textContent;
            let description = row.cells[2].textContent;
            let qty = row.cells[3].querySelector('input').value;
            let unit = row.cells[4].textContent;
            selectedParts.push([partNo, description, qty, unit]); // Add name and email to the row
        }
    }

    // Check if at least one part is selected
    if (selectedParts.length > 1) {
        let orderNo = document.getElementById('displayOB1').innerText;
        let serialNo = document.getElementById('displaySerial4').innerText;
        let itemNo = document.getElementById('displayItemNo5').innerText;
        let description = document.getElementById('displayDescription3').innerText;
        let popRealname = await pop_realname(username);

        try {
            // Generate the Excel file with selected parts
            let { blob, filename } = await downloadExcel(selectedParts, orderNo, serialNo, name, email);

            // Prepare the FormData for file upload
            let formData = new FormData();
            formData.append('file', blob, filename);
            formData.append('username', username);
            formData.append('serialNo', serialNo);
            formData.append('itemNo', itemNo);
            formData.append('description', description);
            formData.append('popRealname', popRealname);
            formData.append('name', name);  // Add name
            formData.append('email', email);  // Add email

            // Send data to the server
            const response = await fetch('order.php', {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                alert('Failed to complete the order process. Please try again.');
                return;
            }

            const data = await response.json();
            console.log('Order submitted:', data);

        } catch (error) {
            console.error('Failed to generate Excel file or send data:', error);
            alert('Failed to complete the order process. Please try again.');
        }
    } else {
        alert('No parts selected!');
    }
});

// ***************** Function to generate Excel file *****************
// Modified downloadExcel to add Name and Email once at the top of the file
function downloadExcel(data, orderNo, serialNo, name, email) {
    return new Promise((resolve, reject) => {
        let ws_name = "SpareParts";
        let wb = XLSX.utils.book_new();

        // Add name and email at the top, followed by the headers for the spare parts
        let excelData = [
            ["Name", name], // Add name
            ["Email", email], // Add email
            [], // Empty row to separate
            ...data // Spare parts data comes after
        ];

        let ws = XLSX.utils.aoa_to_sheet(excelData);
        XLSX.utils.book_append_sheet(wb, ws, ws_name);

        // Get today's date and format it as YYYYMMDD
        let today = new Date();
        let formattedDate = today.toISOString().slice(0, 10).replace(/-/g, "");

        // Create filename using order no, serial no, and today's date
        let filename = `sparepartsorder_${orderNo}_${serialNo}_${formattedDate}.xlsx`;

        try {
            let wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
            let blob = new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

            // Create a link element for downloading the file
            let a = document.createElement('a');
            document.body.appendChild(a);
            let url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = filename;
            a.click();
            setTimeout(() => {
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
            }, 0);

            resolve({ blob, filename });
            console.log("Excel file generated, downloaded, and blob created");
        } catch (error) {
            console.error("Error in generating Excel:", error);
            reject(error);
        }
    });
}



// **************** END **********************************





// Listen for messages from the main window
window.addEventListener('message', function(event) {
    // Check if the message type is 'SET_USERNAME'
    if (event.data && event.data.type === 'SET_USERNAME') {
        // Get the username from the message data
        username = event.data.username;
        
        // Display the welcome message with the username
        const welcomeMessage = document.getElementById('welcomeMessage');
        welcomeMessage.textContent = 'Welcome, ' + username + '!';
    }
});


                // LOGGING Acticvity PART

async function pop_realname(username) {
    try {
        // Fetch the Excel file from the server
        const response = await fetch('USER_DATABASE.xlsx');
        if (!response.ok) {
            console.error('Failed to fetch USER_DATABASE.xlsx');
            return null;
        }

        const arrayBuffer = await response.arrayBuffer();
        const data = new Uint8Array(arrayBuffer);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet);

        // Find the user object in the array whose username matches the provided username
        const user = jsonData.find(u => u['USER DATABASE'] === username); // Adjust 'USER DATABASE' to match the actual key in your Excel data

        // Log if a match is found
        if (user) {
            console.log('Match found for username:', username);
            console.log('Real Name:', user['__EMPTY']); // Adjust '__EMPTY' to match the actual key for real name in your Excel data
        } else {
            console.log('No match found for username:', username);
        }

        // Return the real name or null if not found
        return user ? user['__EMPTY'] : null; // Adjust '__EMPTY' to match the actual key for real name in your Excel data
    } catch (error) {
        console.error("Error fetching or reading Excel data:", error);
        return null;
    }
}

// Function to handle click activity logging
async function logActivity(activityType, details) {
    try {
        let currentDateTime = new Date();
        let date = currentDateTime.toISOString().split('T')[0];
        let time = currentDateTime.toTimeString().split(' ')[0];
        // Fetch the realname
        let popRealname = await pop_realname(username);
        
        // Include machineItemNo in the JSON data
        let postData = {
            activityType,
            date: date,
            time: time,
            details: JSON.stringify(details), // Convert details to a string
            username,  //machineItemNo, // Include machineItemNo
            popRealname
        };

        console.log('postData-Data sent to server:', postData);
        const response = await fetch('log_activity.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(postData)
        });
        if (!response.ok) {
            throw new Error('Error logging activity');
        }
        const data = await response.text();
        console.log('Activity returns from server logged:', data);
        // Log the activity along with the retrieved realname
        console.log('Activity logged activityType, details, popRealname in general :', activityType, details, popRealname);
    } catch (error) {
        console.error('Error logging activity:', error);
    }
}

// Event listener to capture all clicks in the popup window
document.body.addEventListener('click', function(event) {
    const target = event.target;
    const elementType = target.tagName;
    const elementId = target.id;
    const elementText = target.innerText;
    logActivity('click', elementText);
});


function waitForDataAndExecute(callback, retryInterval = 100, maxRetries = 50) {
    let retries = 0;

    const waitForData = setInterval(() => {
        var warrantySpan = document.getElementById('displayWarranty7');
        if (warrantySpan.innerText.trim() !== "") {
            clearInterval(waitForData);
            callback();
        } else if (retries >= maxRetries) {
            clearInterval(waitForData);
            console.log("Max retries reached without data.");
        }
        retries++;
    }, retryInterval);
}

waitForDataAndExecute(function() {
    var warrantySpan = document.getElementById('displayWarranty7');
    console.log("Dynamically loaded warranty date:", warrantySpan.innerText);

    var warrantyParts = warrantySpan.innerText.split('-');
    var warrantyDate = new Date(parseInt(warrantyParts[2], 10), parseInt(warrantyParts[1], 10) - 1, parseInt(warrantyParts[0], 10));
    console.log("Parsed warranty date: ", warrantyDate.toDateString());

    var today = new Date();
    today.setHours(0, 0, 0, 0); // Normalize today's date to midnight for accurate comparison
    console.log("Today's date (normalized): ", today.toDateString());

    var difference = today - warrantyDate; // Difference in milliseconds
    var daysDifference = difference / (1000 * 60 * 60 * 24);
    console.log("Difference in days: ", daysDifference);

    if (daysDifference < 1095) {
        warrantySpan.style.color = 'green';
        console.log("Condition met: Text colored green.");
    } else {
        warrantySpan.style.color = 'red';
        console.log("Condition not met: Text colored red.");
    }
}, 100, 50); // These are the default values for retryInterval and maxRetries, adjust as needed

// Function to show or hide Server Check button based on user role
function toggleServerCheckButton(user) {
    const serverCheckButton = document.getElementById("serverCheckButton");
    if (user.role === "admin") {
        serverCheckButton.style.display = "inline-block"; // Show for admins
    } else {
        serverCheckButton.style.display = "none"; // Hide for non-admins
    }
}

// Listen for messages from the main window
window.addEventListener('message', function(event) {
    if (event.data && event.data.type === 'SET_USERNAME') {
        // Assuming the user object is passed with the event
        const user = event.data.user;

        // Call the function to toggle visibility of the Server Check button
        toggleServerCheckButton(user);
    }
});


function sendSparePartsOrder(fileBlob, otherData) {
    const formData = new FormData();
    formData.append('file', fileBlob, 'spareparts.xlsx');
    formData.append('username', otherData.username);
    formData.append('serialNo', otherData.serialNo);
    formData.append('itemNo', otherData.itemNo);
    formData.append('description', otherData.description);
    formData.append('popRealname', otherData.popRealname);

    fetch('order.php', {
        method: 'POST',
        body: formData,
    })
    .then(response => response.json())
    .then(data => {
        if (data.status_code === 200) {
            console.log('File successfully uploaded to Monday.com');
        } else {
            console.error('Error uploading file:', data.error_message);
        }
    })
    .catch(error => {
        console.error('HTTP error:', error);
    });
}


