let sortAscending = true;
let users = [];
let jsonData = [];
let currentlySortedColumn = -1;
let loggedInUsername = ''; // Global variable to store the logged-in username

// Load login credentials from the JSON file
function loadCredentials() {
    console.log('Initiating fetch...');
    return fetch("credentials.json")
        .then(response => response.json())
        .then(data => {
            users = data;
            console.log('Credentials loaded!');
        })
        .catch(error => {
            console.error("Error fetching credentials:", error);
        });
}

// Load Excel data and convert to JSON
async function loadExcelData() {
    try {
        let response = await fetch("data.xlsx");
        let arrayBuffer = await response.arrayBuffer();
        let data = new Uint8Array(arrayBuffer);
        let workbook = XLSX.read(data, { type: "array" });
        let worksheet = workbook.Sheets[workbook.SheetNames[0]];
        jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, raw: true });
    } catch (error) {
        console.error("Error fetching Excel data:", error);
    }
}

async function login() {
    console.log('Login function called.');
    let username = document.getElementById("username").value.trim();
    let password = document.getElementById("password").value;
    
    if(users.length === 0) {
        console.log('No credentials loaded. Fetching now...');
        await loadCredentials();
    }
    
    console.log('Login function called2.');
    let user = users.find(u => u.username === username && u.password === password);

if (user) {
    loggedInUsername = username; // Store the logged-in username
    document.getElementById("login-message").innerText = "Login successful!";
    document.querySelector(".login-container").style.display = "none";
    document.querySelector(".search-container").style.display = "-webkit-inline-box"; // Show search container
    document.querySelector(".search-buttons").style.display = "flex"; // Show search container
    renderData(user);
    document.querySelector(".table-container").style.display = "block";

    // Send user information to the popup window
    if (popupWindow) {
        popupWindow.postMessage({ type: 'SET_USERNAME', user: user }, '*');
    }
} else {
    document.getElementById("login-message").innerText = "Invalid credentials!";
}
console.log('Login function called3.');

}

// Find realname based on match in user database
async function getRealNameByUsername(username) {
    try {
        const response = await fetch('USER_DATABASE.xlsx');
        if (!response.ok) {
            console.error('Failed to fetch USER_DATABASE.xlsx');
            return null;
        }
        console.log('USER_DATABASE.xlsx fetched successfully');

        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);

        const user = jsonData.find(u => u['USER DATABASE'] === username);
        if (user) {
            console.log('Match found for username:', username);
            console.log('Real Name:', user['__EMPTY']);
        } else {
            console.log('No match found for username:', username);
        }
        return user ? user['__EMPTY'] : null;
    } catch (error) {
        console.error("Error fetching or reading Excel data:", error);
        return null;
    }
}

// Debounce function to limit the rate at which a function can fire
function debounce(func, wait) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
    };
}

// Function to filter the data in memory and render the results
const filterTable = debounce(function(query) {
    console.time("Filtering Time");

    query = query.toLowerCase();
    
    // Get the filtered data based on the logged-in user
    let loggedInUser = users.find(u => u.username === loggedInUsername);

    if (!loggedInUser) {
        console.error("No user found! Unable to filter data.");
        return;
    }

    let filteredData;

    // Admins see all data
    if (loggedInUser.role === "admin") {
        filteredData = jsonData.slice(1); // Exclude headers row
    } else {
        // Regular users only see their filtered rows
        filteredData = jsonData.filter(row => ("" + row[5]).trim() === loggedInUsername);
    }

    // Now filter the data based on the search query
    const searchFilteredData = filteredData.filter(row => 
        row.some(cell => (cell + '').toLowerCase().includes(query))
    );

    // Render the search-filtered data
    renderFilteredData(searchFilteredData);

    console.timeEnd("Filtering Time");
}, 300); // Adjust the debounce wait time as needed


// Set up the search functionality
document.addEventListener("DOMContentLoaded", () => {
    console.log("Document fully loaded and parsed");
    
    let isAutoSearchEnabled = false;

    // Manual search setup
    const searchButton = document.getElementById("search-button");  // Not querying by class but by id
    const searchInput = document.getElementById("search-input");
    const toggleSearchButton = document.getElementById("toggle-search");

    if (searchButton) {
        searchButton.addEventListener("click", function() {
            console.log("Search button clicked");
            const query = searchInput.value;
            filterTable(query);
        });
    } else {
        console.error("Element with ID 'search-button' was not found");
    }

    // Add event listener for "Enter" key to start search
    if (searchInput) {
        searchInput.addEventListener("keydown", function(event) {
            if (event.key === "Enter") {
                console.log("Enter key pressed");
                const query = searchInput.value;
                filterTable(query);
            }
        });

        // Clear search input and reset table when it gains focus
        searchInput.addEventListener("focus", function() {
            searchInput.value = '';
            renderData(users.find(u => u.username === loggedInUsername)); // Reset table
        });
    }

    // Toggle auto-search functionality
    if (toggleSearchButton) {
        toggleSearchButton.addEventListener("click", function() {
            console.log("Toggle button clicked");
            isAutoSearchEnabled = !isAutoSearchEnabled;
            this.innerText = `Auto-Search: ${isAutoSearchEnabled ? "ON" : "OFF"}`;
            
            if (isAutoSearchEnabled) {
                searchInput.addEventListener("input", autoSearch);
            } else {
                searchInput.removeEventListener("input", autoSearch);
            }
        });
    } else {
        console.error("Element with ID 'toggle-search' was not found");
    }

    function autoSearch() {
        console.log("Auto search triggered");
        const query = searchInput.value;
        filterTable(query);
    }
});

function openOptionsModal() {
    document.getElementById('optionsModal').style.display = "block";
}

// Render data into the table
function renderData(user) {
    let table = document.getElementById("data-table");
    table.innerHTML = "";

    let headers = ["Order No", "Customer Name", "Description", "Serial No", "Item No", "Account", "Date", "Reciever"];
    
    // Display headers
    let headerRow = document.createElement("tr");
    headers.forEach((header, index) => {
        let th = document.createElement("th");
        th.style.cursor = "pointer";
        th.onclick = function() {
            sortTable(index);
        };
        
        let span = document.createElement("span");
        span.innerText = header;
        th.appendChild(span);
        
        if (currentlySortedColumn === index) {
            let arrow = document.createElement("span");
            arrow.innerText = sortAscending ? ' ↑' : ' ↓';
            th.appendChild(arrow);
        }

        headerRow.appendChild(th);
    });

    table.appendChild(headerRow);

    let filteredData;
    if (user.role === "admin") {
        filteredData = jsonData.slice(1);
    } else {
        filteredData = jsonData.filter(row => ("" + row[5]).trim() === user.username);
        if(filteredData.length === 0) {
            let tr = document.createElement("tr");
            let td = document.createElement("td");
            td.setAttribute("colspan", "7");
            td.innerText = "No matching data found!";
            tr.appendChild(td);
            
            table.appendChild(tr);
            return;
        }
    }

    filteredData.forEach(row => {
        let tr = document.createElement("tr");
        row.forEach((cell, index) => {
            let td = document.createElement("td");
            td.innerText = (index === 6 && cell) ? formatDate(cell) : cell;
            tr.appendChild(td);
        });
        
        tr.addEventListener("dblclick", function() {
            displayPopup(tr);
        });
        table.appendChild(tr);
    });

    if (user.role === "admin") {
        document.querySelector(".search-container").style.display = "block";
    }
}

// Function to render filtered data
function renderFilteredData(filteredData) {
    let table = document.getElementById("data-table");
    table.innerHTML = ""; // Clear previous content

    let headers = ["Order No", "Customer Name", "Description", "Serial No", "Item No", "Account", "Date", "Reciever"];
    
    // Display headers
    let headerRow = document.createElement("tr");
    headers.forEach((header, index) => {
        let th = document.createElement("th");
        th.style.cursor = "pointer";
        th.onclick = function() {
            sortTable(index); // Allow sorting by clicking the header
        };
        
        let span = document.createElement("span");
        span.innerText = header;
        th.appendChild(span);
        
        if (currentlySortedColumn === index) {
            let arrow = document.createElement("span");
            arrow.innerText = sortAscending ? ' ↑' : ' ↓';
            th.appendChild(arrow);
        }

        headerRow.appendChild(th);
    });
    table.appendChild(headerRow);

    // Populate the table with the filtered data
    if (filteredData.length === 0) {
        let tr = document.createElement("tr");
        let td = document.createElement("td");
        td.setAttribute("colspan", headers.length); // Spanning across all columns
        td.innerText = "No matching data found!";
        tr.appendChild(td);
        table.appendChild(tr);
        return;
    }

    filteredData.forEach(row => {
        let tr = document.createElement("tr");
        row.forEach((cell, index) => {
            let td = document.createElement("td");
            td.innerText = (index === 6 && cell) ? formatDate(cell) : cell; // Formatting date
            tr.appendChild(td);
        });
        
        tr.addEventListener("dblclick", function() {
            displayPopup(tr); // Function to handle row double-clicks
        });

        table.appendChild(tr);
    });
}

// Sort table data
function sortTable(columnIndex) {
    jsonData.sort((a, b) => 
    {
        if (a[columnIndex] < b[columnIndex]) return sortAscending ? -1 : 1;
        if (a[columnIndex] > b[columnIndex]) return sortAscending ? 1 : -1;
        return 0;
    });

    currentlySortedColumn = columnIndex;
    sortAscending = !sortAscending;

    console.log('jsonData:', jsonData); // Check data
    console.log('users:', users); // Check users
    console.log('username value:', document.getElementById("username").value.trim()); // Check username

    let loggedInUser = users.find(u => u.username === document.getElementById("username").value.trim());
    
    if (!loggedInUser) {
        console.error("No user found! Unable to render data.");
        return;
    }

    renderData(loggedInUser);
}

let currentFontSize = 14; // Start with a base font size.

document.getElementById("increaseFontBtn").addEventListener("click", function() {
    currentFontSize += 2;  // Increase font size by 2px
    document.getElementById("data-table").style.fontSize = currentFontSize + "px";
});

document.getElementById("decreaseFontBtn").addEventListener("click", function() {
    currentFontSize -= 2;  // Decrease font size by 2px
    document.getElementById("data-table").style.fontSize = currentFontSize + "px";
});

// Add this function to format your date
function formatDate(serial) {
    const excelEpoch = new Date(1899, 11, 30);
    const excelEpochAsUnixTimestamp = excelEpoch.getTime();
    const millisecondsPerDay = 24 * 60 * 60 * 1000;

    const serialAsUnixTimestamp = serial * millisecondsPerDay;
    const correctSerialDate = new Date(serialAsUnixTimestamp + excelEpochAsUnixTimestamp);

    let day = String(correctSerialDate.getDate()).padStart(2, '0');
    let month = String(correctSerialDate.getMonth() + 1).padStart(2, '0'); // January is 0
    let year = correctSerialDate.getFullYear();

    return `${day}-${month}-${year}`;
}

// Load the Excel data and credentials on page load
loadExcelData();
loadCredentials();

let popupWindow = null;

function displayPopup(row) {
    let itemNoCell = row.children[4];
    let machineItemNo = itemNoCell.innerText;

    if (popupWindow && !popupWindow.closed) {
        popupWindow.close();
    }

    popupWindow = window.open("popup.html?itemNo=" + machineItemNo, "Popup Window", "width=800,height=850");

    const appendDataToPopup = () => {
        let rowData = Array.from(row.children).map(cell => cell.innerText);
        popupWindow.postMessage(rowData, '*');
    };

    popupWindow.onload = function() {
        setTimeout(appendDataToPopup, 1000);
        popupWindow.postMessage({ type: 'SET_USERNAME', username: loggedInUsername }, '*');
    };
}

document.getElementById("password").addEventListener("keyup", function(event) {
    if (event.key === "Enter") {
        login();
        
        document.getElementById("data-table").addEventListener("click", function(event) {
            let rows = this.querySelectorAll("tr");
            rows.forEach(row => row.classList.remove("highlighted-row"));
            if (event.target.tagName === "TD" || event.target.tagName === "TR") {
                let clickedRow = event.target.tagName === "TD" ? event.target.parentElement : event.target;
                clickedRow.classList.add("highlighted-row");
            }
        }); 
    }
});

// Youtube Video modal code
function introvideoOpenModal() {
    document.getElementById('introvideo-modal').style.display = 'block';
}

function introvideoCloseModal() {
    document.getElementById('introvideo-modal').style.display = 'none';
    // Stop the video playback when modal is closed
    var iframe = document.getElementById('introvideo-iframe');
    iframe.src = iframe.src;
}

// LOGGING FUNCTIONALITY

// Global click event listener
document.addEventListener('click', function(event) {
    let element = event.target; // The clicked element
    let details = {
        tagName: element.tagName,
        id: element.id || 'No ID',
        class: element.className || 'No Class',
        text: element.textContent.trim().substring(0, 100) || 'No Text', // Limiting text content to 100 characters
        x: event.clientX,
        y: event.clientY
    };

    // Skip logging if the id is 'No ID' and the text is 'No Text'
    if (details.id === 'No ID' && details.text === 'No Text') {
        return; // Exit the function early without logging
    }

    let detailsString = details.text;
    logActivity('Click', detailsString);
});

// Assuming a function exists to capture clicks, we modify it to include username
function logClick(event) {
    // Capture the clicked element and username
    const clickedElement = event.target;
    const username = document.getElementById('loggedInUsername').textContent; // Example ID for logged-in username

    // Prepare data to be sent to the server
    const data = {
        element: clickedElement.tagName, // Or any other relevant data
        username: username
    };

    // Send data to PHP for logging and user lookup
    fetch('log_activity.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    })
    .then(response => response.json())
    .then(data => {
        console.log('Success:', data);
    })
    .catch((error) => {
        console.error('Error:', error);
    });
}

// logActivity function with separate date and time
async function logActivity(activityType, details) {
    let currentDateTime = new Date();
    let date = currentDateTime.toISOString().split('T')[0]; // YYYY-MM-DD format
    let time = currentDateTime.toTimeString().split(' ')[0]; // HH:MM:SS format

    // Asynchronously retrieve the real name
    let realName = await getRealNameByUsername(loggedInUsername);

    // Construct the activity data including the real name
    let activityData = {
        date: date,
        time: time,
        user: loggedInUsername,
        realname: realName, // Real name is now included after being fetched
        type: activityType,
        details: JSON.stringify(details) // Ensure details are stringified
    };

    // Proceed with sending the activity data to the server
    fetch('log_activity.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(activityData)
    })
    .then(response => response.text())
    .then(data => console.log('Activity logged:', data))
    .catch((error) => console.error('Error:', error));
}
