// localStorage.removeItem('employeesData');

// Open the popup when clicking on the "New" button
document.getElementById('openPopupButton').addEventListener('click', function(event) {
    event.preventDefault(); // Prevent default behavior of the link (if any)
    // Show the popup by changing its display style
    document.getElementById('new-employer-popup-overlay').style.display = 'block';
});

// Close the popup when clicking on the "Close" button inside the popup
document.getElementById('closePopup').addEventListener('click', function() {
    // Hide the popup by setting display to 'none'
    document.getElementById('newEmployerForm').reset();
    document.getElementById('new-employer-popup-overlay').style.display = 'none';
});

/**
 * ----------------------------- 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 === 'employee-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 () {
    const fileInput = document.getElementById('excelFile');
    const file = fileInput.files[0];

    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            const data = e.target.result;
            const workbook = XLSX.read(data, { type: 'binary' });
            const sheetName = workbook.SheetNames[0];
            const sheet = workbook.Sheets[sheetName];
            const excelData = XLSX.utils.sheet_to_json(sheet);

            // Convert Excel data to the required format
            const formattedData = excelData.map(row => ({
                // employeeId1: String(row['Employee ID']) || '',
                employeeId1: row['Employee ID'] || '',
                employeeName: row['Employee Name'] || '',
                department: row['Department'] || '',
                designation: row['Designation'] || '',
                dateOfBirth: excelDateToJSDate(row['Date of Birth']) || '',
                dateOfJoin: excelDateToJSDate(row['Date of Joining']) || '',
                mobile: row['Contact Number'] || '',
                aadharNumber: row['Aadhar Number'] || '',
                category: row['Category'] || '',
                status: row['Status'] || ''
            }));

            // Save the data in employeesData localStorage
            const existingData = JSON.parse(localStorage.getItem('employeesData')) || [];
            const mergedData = mergeEmployeeData(existingData, formattedData);
            localStorage.setItem('employeesData', JSON.stringify(mergedData));

            // Append the new data to the DataTable
            $('#dataTable').DataTable();
            loadEmployees();

            // Close the modal and notify the user
            $('#importModal').modal('hide');
            alert('Employee details imported successfully!');
            window.location.reload();
        };

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

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

$(document).ready(function () {

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

    // 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(); // Moved headerText here
            if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(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 'Status' column and check for visibility
                if (headerText !== 'Image' && headerText !== 'Actions' && 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) => {
            const headerText = header.innerText.trim(); // Moved headerText here
            if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(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 'Status' column and check for visibility
                if (headerText !== 'Image' && headerText !== 'Actions' && 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", "Employeedata.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(); // Moved headerText here
            // Exclude the 'Status' column and check for visibility
            if (headerText !== 'Image' && headerText !== 'Actions' && 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 !== 'Actions' && 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('EmployeeData.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(); // Moved headerText here
            // Exclude the 'Status' column and check for visibility
            if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(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 'Status' column by comparing header text and check for visibility
                if (headerText !== 'Image' && headerText !== 'Actions' && headerText !== 'View Details' && $(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, "EmployeeData.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(); // Moved headerText here
            // Exclude the 'Status' column and check for visibility
            if (headerText !== 'Image' && headerText !== 'Actions' && 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 !== 'Actions' && 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();
    });

});
// 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 load employee data from local storage
function loadEmployees() {
    const employees = JSON.parse(localStorage.getItem('employeesData')) || [];
    const tableBody = document.querySelector('#dataTable tbody');

    // Clear the table
    tableBody.innerHTML = '';

    // Add rows for each employee
    employees.forEach((employee, index) => {
        const newRow = document.createElement('tr');
        // Check if a profile picture exists. If not, use a fallback icon.
        const profilePicture = employee.profilePicture
            ? `<img src="${employee.profilePicture}" alt="Profile Picture" class="profile-img" style="width: 50px; height: 50px; border-radius: 50%;">`
            : `<i class="fas fa-user-circle" style="font-size: 50px; color: #ccc;"></i>`;
        newRow.innerHTML = `
            <td>${employee.employeeId1}</td>
            <td>${profilePicture}</td>
            <td>${employee.employeeName}</td>
            <td>${employee.department}</td>
            <td>${employee.designation}</td>
            <td>${employee.dateOfBirth}</td>
            <td>${employee.dateOfJoin}</td>
            <td>${employee.mobile}</td>
            <td>${employee.aadharNumber}</td>
            <td>${employee.category}</td>
            <td>${employee.status}</td>
            <td>
                <div class="row">
                    <button class="emp-action-btn emp-action-edit" data-index="${index}">
                        <span class="icon" title="Edit"><i class="fas fa-pencil-alt"></i></span>
                    </button>
                    <button class="emp-action-btn emp-action-delete" data-index="${index}">
                        <span class="icon" title="Delete"><i class="fas fa-trash-alt"></i></span>
                    </button>
                </div>
            </td>
        `;
        tableBody.appendChild(newRow);
    });

    // // Reinitialize DataTable after dynamically updating the table body
    // const dataTable = $('#dataTable').DataTable(); // Initialize DataTable instance
    // dataTable.clear(); // Clear existing data
    // dataTable.rows.add($('#dataTable tbody tr')); // Add new rows
    // dataTable.draw(); // Redraw the table to apply changes

    // Add event listeners for edit and delete buttons
    document.querySelectorAll('.emp-action-edit').forEach((btn) =>
        btn.addEventListener('click', handleEditEmployee)
    );
    document.querySelectorAll('.emp-action-delete').forEach((btn) =>
        btn.addEventListener('click', handleDeleteEmployee)
    );
}

// Function to handle edit button click
function handleEditEmployee(event) {
    const index = event.target.closest('button').dataset.index;
    const employees = JSON.parse(localStorage.getItem('employeesData')) || [];
    const employee = employees[index];

    // Prefill the popup form with employee data
    document.getElementById('employeeId').value = employee.employeeId1;
    document.getElementById('employeeName').value = employee.employeeName;
    document.getElementById('DepartmentNameSelect').value = employee.department;
    document.getElementById('designation').value = employee.designation;
    document.getElementById('dateOfBirth').value = convertDateToISO(employee.dateOfBirth);
    document.getElementById('dateOfJoin').value = convertDateToISO(employee.dateOfJoin);
    document.getElementById('Mobile').value = employee.mobile;
    document.getElementById('aadharNumber').value = employee.aadharNumber;
    document.getElementById('CategorySelect').value = employee.category;
    document.getElementById('Status').value = employee.status;

    // Show the popup
    document.getElementById('new-employer-popup-overlay').style.display = 'block';
}

// Function to handle delete button click
function handleDeleteEmployee(event) {
    const index = event.target.closest('button').dataset.index;
    const employees = JSON.parse(localStorage.getItem('employeesData')) || [];
    const employeeId = employees[index].employeeId1;

    // Show confirmation alert
    const confirmDelete = confirm(`Are you sure you want to delete the data of Employee ID: ${employeeId}?`);

    if (confirmDelete) {
        // Remove employee from the list
        employees.splice(index, 1);

        // Save updated employee list to local storage
        localStorage.setItem('employeesData', JSON.stringify(employees));

        // Reload the table
        // loadEmployees();
        window.location.reload();
    }
}

// Load employees on page load
document.addEventListener('DOMContentLoaded', loadEmployees);
// const AllEmployees = JSON.parse(localStorage.getItem('employeesData')) || [];
// $('#dataTable').DataTable().clear().rows.add(AllEmployees).draw();

// Event listener for adding a new employee
document.getElementById('newEmployerForm').addEventListener('submit', function (event) {
    event.preventDefault();

    saveEmployee();

    // Reload the table
    // loadEmployees();
    window.location.reload();

    // Clear the form and hide the popup
    document.getElementById('newEmployerForm').reset();
    document.getElementById('new-employer-popup-overlay').style.display = 'none';
});

// function saveEmployee(){
//     const existingEmployees = JSON.parse(localStorage.getItem('employeesData')) || [];
//     const employee = {
//         employeeId1: document.getElementById('employeeId').value,
//         employeeName: document.getElementById('employeeName').value,
//         department: document.getElementById('DepartmentNameSelect').value,
//         designation: document.getElementById('designation').value,
//         dateOfBirth: convertDateToddmmyyyy(document.getElementById('dateOfBirth').value),
//         dateOfJoin: convertDateToddmmyyyy(document.getElementById('dateOfJoin').value),
//         mobile: document.getElementById('Mobile').value,
//         aadharNumber: document.getElementById('aadharNumber').value,
//         category: document.getElementById('CategorySelect').value,
//         status: document.getElementById('Status').value
//     };

//     // Check if a quotation with the same number already exists
//     const existingIndex = existingEmployees.findIndex(item => item.employeeId1 === employee.employeeId1);

//     if (existingIndex !== -1) {
//         // Quotation with the same number exists
//         const userConfirmation = confirm(`Press 'OK' to overWrite the data of ${employee.employeeId1}?`);

//         if (userConfirmation) {
//             // User confirmed to override, so replace the old data at the found index
//             existingEmployees[existingIndex] = employee;
//             alert(`Employee data has been updated successfully.`);
//         } else {
//             // User canceled, so don't save
//             alert("The data was not saved.");
//             return;
//         }
//     } else {
//         // No existing data with the same quotation number, so add as new
//         existingEmployees.push(employee);
//         console.log(`Employee data saved successfully.`);
//     }

//     // Save the updated data list back to local storage
//     localStorage.setItem('employeesData', JSON.stringify(existingEmployees));
// }

function saveEmployee(){
    // const existingEmployees = JSON.parse(localStorage.getItem('employeesData')) || [];
    
    // Get all form data
    const employeeId1 = document.getElementById('employeeId').value;
    const employeeName = document.getElementById('employeeName').value;
    const department = document.getElementById('DepartmentNameSelect').value;
    const designation = document.getElementById('designation').value;
    const dateOfBirth = convertDateToddmmyyyy(document.getElementById('dateOfBirth').value);
    const dateOfJoin = convertDateToddmmyyyy(document.getElementById('dateOfJoin').value);
    const mobile = document.getElementById('Mobile').value;
    const aadharNumber = document.getElementById('aadharNumber').value;
    const category = document.getElementById('CategorySelect').value;
    const status = document.getElementById('Status').value;

    // Get profile picture file
    const profilePicture = document.getElementById('profilePicture').files[0];

    let employee = {
        employeeId1,
        employeeName,
        department,
        designation,
        dateOfBirth,
        dateOfJoin,
        mobile,
        aadharNumber,
        category,
        status,
        profilePicture: null // Default to null for the profile picture
    };

    // If a profile picture is provided, read it as a base64 string
    if (profilePicture) {
        const reader = new FileReader();
        
        reader.onloadend = function() {
            // After the file is read, set the profile picture field
            employee.profilePicture = reader.result; // Base64 encoded string

            // Process the employee data and save it
            saveEmployeeData(employee);
        };

        // Read the file as a data URL (base64 string)
        reader.readAsDataURL(profilePicture);
    } else {
        // If no profile picture, simply save the employee data
        saveEmployeeData(employee);
    }
}

function saveEmployeeData(employee) {
    const existingEmployees = JSON.parse(localStorage.getItem('employeesData')) || [];

    // Check if an employee with the same ID already exists
    const existingIndex = existingEmployees.findIndex(item => item.employeeId1 === employee.employeeId1);

    if (existingIndex !== -1) {
        // Employee with the same ID exists, ask for confirmation to overwrite
        const userConfirmation = confirm(`Press 'OK' to overwrite the data of employee ID: ${employee.employeeId1}?`);
        
        if (userConfirmation) {
            existingEmployees[existingIndex] = employee; // Overwrite existing data
            alert(`Employee data has been updated successfully.`);
        } else {
            alert("The data was not saved.");
            return;
        }
    } else {
        // No existing data with the same ID, add new employee
        existingEmployees.push(employee);
        alert(`Employee data saved successfully.`);
    }

    // Save the updated employee list to local storage
    localStorage.setItem('employeesData', JSON.stringify(existingEmployees));
}

// Merge new employee data with existing, avoiding duplicates
function mergeEmployeeData(existingData, newData) {
    newData.forEach(newEmployee => {
        const existingIndex = existingData.findIndex(emp => emp.employeeId1 === newEmployee.employeeId1);
        if (existingIndex !== -1) {
            // Replace existing employee data with the new one
            existingData[existingIndex] = newEmployee;
        } else {
            // Add new employee data
            existingData.push(newEmployee);
        }
    });
    return existingData;
}

// function mergeEmployeeData(existingData, newData) {
//     newData.forEach(newEmployee => {
//         const existingIndex = existingData.findIndex(emp => emp.employeeId1 === newEmployee.employeeId1);

//         if (existingIndex !== -1) {
//             // Optional: Ask for confirmation before overwriting existing data
//             const confirmOverwrite = confirm(`Employee ID ${newEmployee.employeeId1} already exists. Do you want to overwrite the data?`);
//             if (confirmOverwrite) {
//                 // Replace existing employee data with the new one
//                 existingData[existingIndex] = newEmployee;
//             }
//         } else {
//             // Add new employee data if not already present
//             existingData.push(newEmployee);
//         }
//     });

//     return existingData;
// }

// Function to convert Excel numeric date to JavaScript Date
function excelDateToJSDate(excelDate) {
    if (!excelDate) return '';
    const parsedDate = new Date((excelDate - 25569) * 86400 * 1000);
    const day = String(parsedDate.getDate()).padStart(2, '0');
    const month = String(parsedDate.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
    const year = parsedDate.getFullYear();
    return `${day}-${month}-${year}`;
}
// Utility function to convert DD-MM-YYYY to YYYY-MM-DD
function convertDateToISO(dateString) {
    if (!dateString) return ''; // Return empty string for invalid or empty date
    const [day, month, year] = dateString.split('-');
    return `${year}-${month}-${day}`;
}
// Utility function to convert DD-MM-YYYY to YYYY-MM-DD
function convertDateToddmmyyyy(dateString) {
    if (!dateString) return ''; // Return empty string for invalid or empty date
    const [year, month, day] = dateString.split('-');
    return `${day}-${month}-${year}`;
}
console.log(JSON.parse(localStorage.getItem('employeesData')));  // Check the structure of the existing data