window.addEventListener('load', async () => {

    // localStorage.removeItem('rcDataList');

    document.getElementById('routeNo').value = generateRCId();
    addRow();
    populateCompanyNames();
    document.getElementById('companyNameSelect').addEventListener('change', handlecompanySelection);

    document.getElementById("productType").addEventListener("change", function () {
        const otherInput = document.getElementById("other-product-input");
        otherInput.style.display = this.value === "other" ? "block" : "none";
    });

    // edit codeis in populateCompanyNames() for company name selection purpose 

    //Get today's date in YYYY-MM-DD format
    const today = new Date().toISOString().split('T')[0];
    // Set the default value of the date input to today's date
    document.getElementById('routeDate').value = today;

    // Call the function to populate options
    populateGrnOptions();

});
// Event listener for the submit button to save the form data
document.getElementById('routeForm').addEventListener('submit', function (event) {
    event.preventDefault();

    const productType = document.getElementById("productType").value.trim() || null;
    const otherProductType = document.getElementById("other-product-type").value.trim() || null;

    const finalProductType = productType === 'other' ? otherProductType : productType;

    // Create an object to store form data
    const routeCardData = {
        rcId: document.getElementById('routeNo').value,
        rcDate: document.getElementById('routeDate').value,
        grnId: document.getElementById('grnNo').value,
        grnDate: document.getElementById('grnDate').value,
        orderId: document.getElementById('orderNo').value,
        orderDate: document.getElementById('orderDate').value,
        companyName: document.getElementById('companyNameSelect').value,
        orderRefNo: document.getElementById('orderRefNo').value,
        address: document.getElementById('companyAddress').value,
        gstNo: document.getElementById('companyGSTN').value,
        email: document.getElementById('companyEmail').value,
        phone: document.getElementById('companyPhone').value,
        quotationId: document.getElementById('quotationNo').value,
        quotationDate: document.getElementById('quotationDate').value,
        rfqNo: document.getElementById('rfqNo').value,
        rfqDate: document.getElementById('rfqDate').value,
        partNo: document.getElementById('partNo').value,
        projectMaterialNo: document.getElementById('project-materialNo').value,
        drawingNo: document.getElementById('drawingNo').value,
        drawingRev: document.getElementById('drawingRev').value,
        description: document.getElementById('description').value,
        productType: finalProductType,
        projectStart: document.getElementById('projectStart').value,
        status: 'Waiting for approval',
        productProcesses: []
    };

    // Fetch data from product process table
    const tableRows = document.querySelectorAll('#productTable tbody tr');
    tableRows.forEach(row => {
        const process = row.querySelector('.process').value || null;
        // Get the selected radio button (Inhouse or Outsourced)
        const inhouse = row.querySelector('.inhouse').checked  || null;
        const outsourced = row.querySelector('.outsourced').checked || null;
        const previousProcess = row.querySelector('.previousProcess').value || null;
        const machine = row.querySelector('.machine').value || null;
        const operator = row.querySelector('.operator').value || null;
        const ctHours = row.querySelector('.hours').value || null;
        const ctMinutes = row.querySelector('.minutes').value || null;

        // Check if any data is filled out
        if (process || inhouse || outsourced || previousProcess || machine || operator || ctHours || ctMinutes) {
            routeCardData.productProcesses.push({
                process,
                source: inhouse ? 'Inhouse' : 'Outsourced',
                previousProcess,
                machine,
                operator,
                ctHours,
                ctMinutes
            });
        }
    });

    // Retrieve existing data from localStorage
    const existingData = JSON.parse(localStorage.getItem('rcDataList')) || [];
    const existingIndex = existingData.findIndex(data => data.rcId === routeCardData.rcId);

    // Check for duplicate rcId and confirm overwrite
    if (existingIndex !== -1) {
        const confirmOverwrite = confirm(`Route Card with RC ID '${routeCardData.rcId}' already exists. Do you want to overwrite it?`);
        if (!confirmOverwrite) {
            sessionStorage.removeItem('currentRCId');
            window.location.reload();
            return;
        }
        existingData[existingIndex] = routeCardData; // Overwrite existing entry
    } else {
        existingData.push(routeCardData); // Add new entry
    }

    // Save updated data to localStorage
    localStorage.setItem('rcDataList', JSON.stringify(existingData));

    alert('Route Card Data Saved Successfully!');
    routeForm.reset(); // Reset the form after submission
    sessionStorage.removeItem('currentRCId');
    window.location.href = 'route-card-datatable.html';
});
document.getElementById('rcContent').addEventListener('keydown', function (event) {
    // Check if the pressed key is "Enter" (keyCode 13 or event.code 'Enter')
    if (event.key === "Enter") {
        // Prevent form submission
        event.preventDefault();

        // Move focus to the next input field (you can customize this if needed)
        let currentInput = document.activeElement;
        let nextInput = currentInput.nextElementSibling;

        // If the next input exists and it's an input field, focus on it
        while (nextInput && nextInput.tagName.toLowerCase() !== 'input') {
            nextInput = nextInput.nextElementSibling;
        }

        if (nextInput) {
            nextInput.focus();
        }
    }
});
// Function to generate the GRN ID
function generateRCId() {
    const savedData = JSON.parse(localStorage.getItem('rcDataList')) || [];
    const lastRC = savedData.length ? savedData[savedData.length - 1].rcId : "UEPL/RC/0000";
    const lastIdNumber = parseInt(lastRC.split('/').pop(), 10);
    const newIdNumber = (lastIdNumber + 1).toString().padStart(4, '0');
    return `UEPL/RC/${newIdNumber}`;
}
function resetForm() {
    document.getElementById('grnForm').reset();
    document.querySelector(".product-table tbody").innerHTML = '';
    addRow();
}
async function populateCompanyNames() {
    try {
        const response = await fetch('https://umbreyengineering.com/api/customer/');
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const companyData = await response.json();
        const companyName = document.getElementById("companyNameSelect");
        companyData.forEach(company => {
            const companyId1 = company.companyId1;
            if (companyId1 && (companyId1.startsWith('UEPL/CUS/') || companyId1.startsWith('UEPL/CV/') || companyId1.startsWith('UEPL/VEN/'))) {
                const option1 = document.createElement("option");
                option1.value = company.companyName;
                option1.textContent = company.companyName;
                companyName.appendChild(option1);
            }
        });

        // edit code for company name selection purpose
        let savedData = [];
        let rcData = null;
        let editRCData = null;

        const editRCId = sessionStorage.getItem('currentRCId');
        const viewRCId = sessionStorage.getItem('viewRCId');

        if (editRCId) {
            // Retrieve the grn data list from local storage
            savedData = JSON.parse(localStorage.getItem('rcDataList')) || [];

            rcData = savedData.find(item => item.rcId === editRCId);
            if (rcData) {
                editRCData = rcData;
            }
        }else if (viewRCId) {
            // Retrieve the grn data list from local storage
            savedData = JSON.parse(localStorage.getItem('rcDataList')) || [];

            rcData = savedData.find(item => item.rcId === viewRCId);
            if (rcData) {
                editRCData = rcData;
            }
            // Disable input, textarea, select fields
            const formElements = document.querySelectorAll('input, textarea, select');
            formElements.forEach(element => {
                element.disabled = true;  // Makes the fields readonly or uneditable
            });

            // Hide all buttons
            const buttons = document.querySelectorAll('button');
            buttons.forEach(button => {
                button.style.display = 'none';  // Hides the button
            });
        }
        if (editRCData) {
            document.getElementById('routeNo').value = editRCData.rcId || '';
            document.getElementById('routeDate').value = editRCData.rcDate || '';
            document.getElementById('grnNo').value = editRCData.grnId || '';
            document.getElementById('grnDate').value = editRCData.grnDate || '';
            document.getElementById('orderNo').value = editRCData.orderId || '';
            document.getElementById('orderDate').value = editRCData.orderDate || '';
            document.getElementById('companyNameSelect').value = editRCData.companyName || '';
            document.getElementById('orderRefNo').value = editRCData.orderRefNo || '';
            document.getElementById('companyAddress').value = editRCData.address || '';
            document.getElementById('companyGSTN').value = editRCData.gstNo || '';
            document.getElementById('companyEmail').value = editRCData.email || '';
            document.getElementById('companyPhone').value = editRCData.phone || '';
            document.getElementById('quotationNo').value = editRCData.quotationId || '';
            document.getElementById('quotationDate').value = editRCData.quotationDate || '';
            document.getElementById('rfqNo').value = editRCData.rfqNo || '';
            document.getElementById('rfqDate').value = editRCData.rfqDate || '';
            document.getElementById('partNo').value = editRCData.partNo || '';
            document.getElementById('project-materialNo').value = editRCData.projectMaterialNo || '';
            document.getElementById('drawingNo').value = editRCData.drawingNo || '';
            document.getElementById('drawingRev').value = editRCData.drawingRev || '';
            document.getElementById('description').value = editRCData.description || '';
            document.getElementById('projectStart').value = editRCData.projectStart || '';

            // Handle productType
            const productTypeElement = document.getElementById('productType');
            const otherProductInputElement = document.getElementById('other-product-input');
            const otherProductTypeElement = document.getElementById('other-product-type');

            // Check if editRCData.productType matches the available options
            const productTypeExists = Array.from(productTypeElement.options).some(option => option.value === editRCData.productType);

            if (!productTypeExists || editRCData.productType === 'other') {
                productTypeElement.value = 'other';
                otherProductInputElement.style.display = 'block';
                otherProductTypeElement.value = editRCData.productType || '';
            } else {
                productTypeElement.value = editRCData.productType;
            }
            populateTableDetails(editRCData.productProcesses || []);
        }
        sessionStorage.removeItem('currentRCId');
        sessionStorage.removeItem('viewRCId');
    } catch (error) {
        console.error("Error fetching company data:", error);
    }
}
// Function to add a new row with event listeners
function addRow() {
    const productTableBody = document.querySelector(".product-table tbody");

    if (!productTableBody) {
        console.error("Table body not found! Ensure the table exists in the DOM.");
        return;
    }

    const newRow = document.createElement("tr");

    newRow.innerHTML = `
        <td>${productTableBody.rows.length + 1}</td>
        <td><input type="text" class="process" placeholder="Process" list="processList-${productTableBody.rows.length + 1}"></td>
        <td>
            <label><input type="radio" name="source-${productTableBody.rows.length + 1}" class="inhouse" value="inhouse" oninput="updateSource(this)" checked> Inhouse</label>
            <label><input type="radio" name="source-${productTableBody.rows.length + 1}" class="outsourced" value="outsourced" oninput="updateSource(this)"> Outsourced</label>
        </td>
        <td><input type="text" class="previousProcess" placeholder="Previous Process" list="processList-${productTableBody.rows.length + 1}"></td>
        <td><input type="text" class="machine" placeholder="Machine" list="machineList-${productTableBody.rows.length + 1}"></td>
        <td><input type="text" class="operator" placeholder="Operator" list="operatorList-${productTableBody.rows.length + 1}"></td>
        <td>
            <input type="number" class="hours" placeholder="Hours" min="0" step="1" style="width: 45%;">
            <span>:</span>
            <input type="number" class="minutes" placeholder="Minutes" min="0" max="59" step="1" style="width: 45%;">
        </td>
        <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
    `;

    productTableBody.appendChild(newRow);

    // Create and append datalists for new row
    createDatalist(`processList-${productTableBody.rows.length}`, []);
    createDatalist(`machineList-${productTableBody.rows.length}`, []);
    createDatalist(`operatorList-${productTableBody.rows.length}`, []);
}
function createDatalist(id, options) {
    let datalist = document.createElement("datalist");
    datalist.id = id;
    options.forEach(optionValue => {
        let option = document.createElement("option");
        option.value = optionValue;
        datalist.appendChild(option);
    });
    document.body.appendChild(datalist);
}
// Delete a row from the product table
function deleteRow(button) {
    const row = button.parentNode.parentNode;
    row.parentNode.removeChild(row);
}
// Print the RC
function printRC() {
    const bodyElements = document.body.children;
    const rcContent = document.getElementById("rcContent");

    // Hide all elements except the quotation content
    for (let i = 0; i < bodyElements.length; i++) {
        if (bodyElements[i] !== rcContent) {
            bodyElements[i].style.visibility = "hidden";
        }
    }

    // Hide all buttons inside the quotation content
    const buttons = rcContent.getElementsByTagName("button");
    for (let i = 0; i < buttons.length; i++) {
        buttons[i].style.visibility = "hidden";
    }

    // Make quotation content and its children visible
    rcContent.style.visibility = "visible";
    for (let i = 0; i < rcContent.children.length; i++) {
        rcContent.children[i].style.visibility = "visible";
    }

    // Print the page with only the quotation content visible
    window.print();

    // Restore visibility of other elements after printing
    for (let i = 0; i < bodyElements.length; i++) {
        if (bodyElements[i] !== rcContent) {
            bodyElements[i].style.visibility = "";
        }
    }

    // Restore visibility of buttons in the quotation content
    for (let i = 0; i < buttons.length; i++) {
        buttons[i].style.visibility = "";
    }
}
// Save the GRN (basic simulation)
function saveRC() {
    //   alert('Quotation saved successfully!');
    // generatePDF();
}
// Function to convert file to Base64
function fileToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function (event) {
            resolve(event.target.result); // Base64 encoded string
        };
        reader.onerror = function (error) {
            reject(error);
        };
        reader.readAsDataURL(file);
    });
}
// Function to format the current date as dd-mm-yyyy
function formatDate(date) {
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
    const year = date.getFullYear();
    return `${day}-${month}-${year}`;
}
// Handle company selection and populate related fields
async function handlecompanySelection() {
    const selectedCompany = document.getElementById('companyNameSelect').value;

    try {
        const response = await fetch('https://umbreyengineering.com/api/customer/');
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const dataList = await response.json();
        const filteredData = dataList.filter(data => data.companyName === selectedCompany);

        if (filteredData && filteredData.length > 0) {
            const { billingAddress, gstNo, companyContact, companyEmail } = filteredData[0];
            document.getElementById('companyAddress').value = billingAddress;
            document.getElementById('companyGSTN').value = gstNo;
            document.getElementById('companyPhone').value = companyContact;
            document.getElementById('companyEmail').value = companyEmail;
        }
        else {
            document.getElementById('companyAddress').value = '';
            document.getElementById('companyGSTN').value = '';
            document.getElementById('companyPhone').value = '';
            document.getElementById('companyEmail').value = '';
        }
    } catch (error) {
        console.error("Error fetching company data:", error);
    }
}
function populateTableDetails(products) {
    const productTableBody = document.querySelector('.product-table tbody');
    productTableBody.innerHTML = '';
    let index = productTableBody.rows.length;

    products.forEach((product) => {
        const row = document.createElement("tr");

        // Determine the selected source (Inhouse or Outsourced)
        const inhouseChecked = product.source === 'Inhouse' ? 'checked' : '';
        const outsourcedChecked = product.source === 'Outsourced' ? 'checked' : '';

        row.innerHTML = `
            <td>${index + 1}</td>
            <td><input type="text" class="process" value="${product.process || ''}" list="processList-${productTableBody.rows.length + 1}" placeholder="Process"></td>
            <td>
                <label><input type="radio" name="source-${index + 1}" class="inhouse" value="inhouse" oninput="updateSource(this)" ${inhouseChecked}> Inhouse</label>
                <label><input type="radio" name="source-${index + 1}" class="outsourced" value="outsourced" oninput="updateSource(this)" ${outsourcedChecked}> Outsourced</label>
            </td>
            <td><input type="text" class="previousProcess" value="${product.previousProcess || ''}" list="processList-${productTableBody.rows.length + 1}" placeholder="Previous Process"></td>
            <td><input type="text" class="machine" value="${product.machine || ''}" list="machineList-${productTableBody.rows.length + 1}" placeholder="Machine"></td>
            <td><input type="text" class="operator" value="${product.operator || ''}" list="operatorList-${productTableBody.rows.length + 1}" placeholder="Operator"></td>
            <td>
                <input type="number" class="hours" value="${product.ctHours}" placeholder="Hours" min="0" step="1" style="width: 45%;">
                <span>:</span>
                <input type="number" class="minutes" value="${product.ctMinutes}" placeholder="Minutes" min="0" max="59" step="1" style="width: 45%;">
            </td>
            <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
        `;

        productTableBody.appendChild(row);

        // Create and append datalists for new row
        createDatalist(`processList-${productTableBody.rows.length}`, []);
        createDatalist(`machineList-${productTableBody.rows.length}`, []);
        createDatalist(`operatorList-${productTableBody.rows.length}`, []);

        const viewRCId = sessionStorage.getItem('viewRCId');

        if (viewRCId) {
            // Disable all input, textarea, and select fields inside the #productTable
            const table = document.querySelector('#productTable');
            const formElements = table.querySelectorAll('input, textarea, select, button');
            
            formElements.forEach(element => {
                if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.tagName === 'SELECT') {
                    element.disabled = true; // Makes the fields readonly or uneditable
                } else if (element.tagName === 'BUTTON') {
                    element.style.display = 'none';  // Hides the buttons
                }
            });
        }
        updateProcessDatalist();
        index++;
    });
}
// Function to print the saved RC data from localStorage
function printSavedRCData() {
    // Retrieve the saved data from localStorage
    const rcDataList = JSON.parse(localStorage.getItem('rcDataList'));

    // Check if there is any saved data
    if (rcDataList && rcDataList.length > 0) {
        // Print the saved RC data in the console
        console.log("Saved RC Data:", rcDataList);
    } else {
        // If no data is found, print a message
        console.log("No RC data found in localStorage.");
    }
}
// Populate RC ID dropdown with unique values from grnDataList
function populateGrnOptions() {
    const grnDataList = JSON.parse(localStorage.getItem('grnDataList')) || [];
    const uniqueGrnIds = [...new Set(grnDataList.map(data => data.grnNo1))];

    const grnNoInput = document.getElementById('grnNo');
    const grnDataListElement = document.createElement('datalist');
    grnDataListElement.id = 'grnOptions';

    uniqueGrnIds.forEach(grnId => {
        const selectedGrnData = grnDataList.find(data => data.grnNo1 === grnId);
        if (grnId) {
            const option = document.createElement('option');
            option.value = grnId;
            option.textContent = `${selectedGrnData.companyName || ''}`;
            grnDataListElement.appendChild(option);
        }
    });

    grnNoInput.setAttribute('list', 'grnOptions');
    document.body.appendChild(grnDataListElement);

    // Attach event listener to populate related fields on selection
    grnNoInput.addEventListener('input', function () {
        const selectedGrnData = grnDataList.find(data => data.grnNo1 === grnNoInput.value);
        if (selectedGrnData) {
            document.getElementById('grnDate').value = selectedGrnData.grnDate1 || '';
            document.getElementById('orderNo').value = selectedGrnData.orderNo || '';
            document.getElementById('orderDate').value = selectedGrnData.orderDate || '';
            document.getElementById('companyNameSelect').value = selectedGrnData.companyName || '';
            document.getElementById('companyAddress').value = selectedGrnData.companyAddress || '';
            document.getElementById('orderRefNo').value = selectedGrnData.orderRefNo || '';
            document.getElementById('companyGSTN').value = selectedGrnData.companyGSTN || '';
            document.getElementById('companyPhone').value = selectedGrnData.companyPhone || '';
            document.getElementById('companyEmail').value = selectedGrnData.companyEmail || '';
            document.getElementById('quotationNo').value = selectedGrnData.quotationNo || '';
            document.getElementById('quotationDate').value = selectedGrnData.quotationDate || '';
            document.getElementById('rfqNo').value = selectedGrnData.rfqNo || '';
            document.getElementById('rfqDate').value = selectedGrnData.rfqDate || '';
            document.getElementById('partNo').value = selectedGrnData.partNo || '';
            document.getElementById('project-materialNo').value = selectedGrnData.projectMaterialNo || '';
            document.getElementById('drawingNo').value = selectedGrnData.drawingNo || '';
            document.getElementById('drawingRev').value = selectedGrnData.drawingRev || '';
            document.getElementById('description').value = selectedGrnData.description || '';
            // document.getElementById('productType').value = selectedGrnData.productType || '';

            // Handle productType
            const productTypeElement = document.getElementById('productType');
            const otherProductInputElement = document.getElementById('other-product-input');
            const otherProductTypeElement = document.getElementById('other-product-type');

            // Check if selectedGrnData.productType matches the available options
            const productTypeExists = Array.from(productTypeElement.options).some(option => option.value === selectedGrnData.productType);

            if (!productTypeExists || selectedGrnData.productType === 'other') {
                productTypeElement.value = 'other';
                otherProductInputElement.style.display = 'block';
                otherProductTypeElement.value = selectedGrnData.productType || '';
            } else {
                productTypeElement.value = selectedGrnData.productType;
            }
        }
        updateProcessDatalist();
    });
}
function updateSource(selectElement) {
    const selectedSource = selectElement.value;

    // Get the row where the dropdown is located
    const row = selectElement.closest('tr');

    // Get the input elements for Size 1, Size 2, and Size 3
    const machine = row.querySelector('.machine');
    const operator = row.querySelector('.operator');
    // Set the placeholder based on the selected type
    if (selectedSource === 'inhouse') {
        machine.readOnly = false;
        operator.readOnly = false;
    } else if (selectedSource === 'outsourced') {
        machine.readOnly = true;
        operator.readOnly = true;
        machine.value = '';
        operator.value = '';
    }
}
// -------------------------------------------------For Data List's Creation----------------------------------------------------------------

const productTypeInput = document.getElementById("productType");
const productTable = document.getElementById("productTable");
const processOptions = {
    round: ["RM Testing", "RM Cutting", "Facing & Centering", "Pre Turning", "CNC Turning", "Face Hole", "Cross Hole", "Deep Hole Drilling",
        "Re Centring", "Key Way Milling", "Grinding", "Burnishing", "Face Hole tapping", "Deburring & Cleaning","Final Inspection", "Packing"],
    rib: ["RM Testing", "RM Cutting", "Facing & Centering", "Pre Turning", "Plate Cutting", "Plate Drilling", "Chamfering",
        "RIB Setting", "Root Welding", "SAW Welding", "DP Testing 1", "Face Welding", "Grinding", "Stress Relieving", "Shot Blasting",
        "DP Testing 2", "CNC Turning", "Face Hole", "Cross Hole", "Deep Hole Drilling", "Re Centring", "Key Way Milling", "Grinding",
        "Burnishing", "Face Hole tapping", "Deburring & Cleaning", "Final Inspection", "Packing"]
};
const machineOptions = {
    "RM Cutting": ["1001-Laser Cutter", "Waterjet Cutter"],
    "Facing & Centering": ["CNC Milling Machine", "Centering Machine"],
    "Pre Turning": ["CNC Lathe", "Manual Lathe"],
    "CNC Turning": ["CNC Lathe", "CNC Mill"],
    "Face Hole": ["CNC Drilling Machine", "Radial Drill"],
    "Cross Hole": ["CNC Drilling Machine", "Radial Drill"],
    "Deep Hole Drilling": ["CNC Lathe", "CNC Milling Machine"],
    "Re Centring": ["CNC Lathe", "CNC Milling Machine"],
    "Key Way Milling": ["CNC Milling Machine", "Manual Milling Machine"],
    "Grinding": ["Surface Grinder", "Cylindrical Grinder"],
    "Burnishing": ["Polishing Machine", "Grinding Machine"],
    "Face Hole Tapping": ["CNC Milling Machine", "Tapping Machine"],
    "Deburring & Cleaning": ["Deburring Machine", "Pressure Washer"],

    // Rib Process Machines
    "Plate Cutting": ["Plasma Cutter", "Laser Cutter"],
    "Plate Drilling": ["CNC Drilling Machine", "Manual Drill"],
    "Chamfering": ["CNC Milling Machine", "Chamfering Machine"],
    "RIB Setting": ["Rib Setting Machine", "Rib Placement Machine"],
    "Root Welding": ["MIG Welder", "TIG Welder"],
    "Saw Welding": ["Plasma Cutter", "Sawing Machine"],
    "DP Testing 1": ["Inspection Machine", "Visual Inspection Station"],
    "Face Welding": ["MIG Welder", "TIG Welder"],
    "Grinding": ["Cylindrical Grinder", "Surface Grinder"],
    "Stress Relieving": ["Stress Relieving Furnace", "Thermal Processing Oven"],
    "Shot Blasting": ["Shot Blasting Machine", "Blasting Station"],
    "DP Testing 2": ["Ultrasonic Testing Machine", "Magnetic Testing Machine"],
    "CNC Turning 2": ["CNC Lathe", "CNC Mill"],
    "Re Centring": ["CNC Lathe", "CNC Milling Machine"],
    "Key Way Milling": ["CNC Milling Machine", "Manual Milling Machine"]
};
const operatorOptions = {
    "Laser Cutter": ["John Doe", "Alice Brown"],
    "Waterjet Cutter": ["Bob White", "Eve Adams"],
    "CNC Milling Machine": ["Charlie Green", "Grace Hall"],
    "CNC Lathe": ["David Black", "Frank Wilson"],
    "Surface Grinder": ["Ivy Clark", "Jack Lewis"],
    "Radial Drill": ["Kevin Young", "Sophia Mitchell"],
    "Manual Lathe": ["Liam Turner", "Noah Wright"],
    "Plasma Cutter": ["Olivia Walker", "Paul Evans"],
    "CNC Drilling Machine": ["Quinn Baker", "Ryan Carter"],
    "Polishing Machine": ["Sophia Mitchell", "Tom Rogers"],
    "Tapping Machine": ["Uma Lopez", "Victor Perez"],
    "Deburring Machine": ["Walter Scott", "Zara Lee"],
    "MIG Welder": ["Mia Harris", "Noah Wright"],
    "TIG Welder": ["Olivia Walker", "Paul Evans"],
    "Shot Blasting Machine": ["Grace Hall", "Henry Scott"],
    "Stress Relieving Furnace": ["Ivy Clark", "Jack Lewis"],
    "Testing Machine": ["Liam Turner", "Mia Harris"],
    "Metrology Equipment": ["Liam Turner", "Mia Harris"],
    "Ultrasonic Testing Machine": ["Liam Turner", "Mia Harris"],
    "Magnetic Testing Machine": ["Sophia Mitchell", "Tom Rogers"],
    "Cylindrical Grinder": ["Alice Brown", "Bob White"],
    "Manual Milling Machine": ["Frank Wilson", "Kevin Young"],
    "Rib Setting Machine": ["Paul Evans", "Olivia Walker"],
    "Injection Molder": ["Ivy Clark", "Tom Rogers"],
    "Sawing Machine": ["Grace Hall", "Henry Scott"]
};

function updateProcessDatalist() {
    if (productTypeInput.value.toLowerCase() === "Round Shaft".toLowerCase()) {
        const productType = 'round';
        document.querySelectorAll(".process").forEach(input => {
            input.list.innerHTML = "";
            if (processOptions[productType]) {
                processOptions[productType].forEach(process => {
                    let option = document.createElement("option");
                    option.value = process;
                    input.list.appendChild(option);
                });
            }
        });
        document.querySelectorAll(".previousProcess").forEach(input => {
            input.list.innerHTML = "";
            if (processOptions[productType]) {
                processOptions[productType].forEach(process => {
                    let option = document.createElement("option");
                    option.value = process;
                    input.list.appendChild(option);
                });
            }
        });
    } else if (productTypeInput.value.toLowerCase() === "Rib Shaft".toLowerCase()) {
        const productType = 'rib';
        document.querySelectorAll(".process").forEach(input => {
            input.list.innerHTML = "";
            if (processOptions[productType]) {
                processOptions[productType].forEach(process => {
                    let option = document.createElement("option");
                    option.value = process;
                    input.list.appendChild(option);
                });
            }
        });
        document.querySelectorAll(".previousProcess").forEach(input => {
            input.list.innerHTML = "";
            if (processOptions[productType]) {
                processOptions[productType].forEach(process => {
                    let option = document.createElement("option");
                    option.value = process;
                    input.list.appendChild(option);
                });
            }
        });
    }
}

function updateMachineDatalist(event) {
    const processValue = event.target.value;
    const machineInput = event.target.closest("tr").querySelector(".machine");
    machineInput.list.innerHTML = "";
    let machineData = JSON.parse(localStorage.getItem("MachineOccupancyData")) || {};
    // Create an array to store option elements
    let optionsArray = [];
    if (machineOptions[processValue]) {
        machineOptions[processValue].forEach(machine => {
            let machineOccupancy = machineData[machine] || [];  // Get the occupancy data for the specific machine
            // Find the maximum end date
            let maxEndDate = null;
            let formattedDate = formatDateWithCustomLocale(Date.now());

            machineOccupancy.forEach(occupancy => {
                let endDate = new Date(occupancy.end);  // Convert to Date object
                if (!maxEndDate || endDate > maxEndDate) {
                    maxEndDate = endDate;  // Update maxEndDate if the current endDate is later
                }
                if (maxEndDate > Date.now()) {
                    formattedDate = formatDateWithCustomLocale(maxEndDate);
                    return formattedDate;
                }
            });
            
            let option = document.createElement("option");
            option.value = machine;
            option.textContent = `Available from: ${formattedDate}`;  // Display the formatted date in the option text
            // machineInput.list.appendChild(option);
            // Add the option to the optionsArray
            // Store the maxEndDate as a timestamp in a data attribute
            option.setAttribute("data-end", maxEndDate ? maxEndDate.getTime() : Date.now());

            // Add the option to the optionsArray
            optionsArray.push(option);
        });
    }
    // Sort the options based on the data-end attribute (ascending order)
    optionsArray.sort((a, b) => {
        let aDate = parseInt(a.getAttribute("data-end"), 10);  // Get the timestamp from the data-end attribute
        let bDate = parseInt(b.getAttribute("data-end"), 10);  // Get the timestamp from the data-end attribute
        return aDate - bDate;  // Sort in ascending order
    });

    // Append all sorted options to the input field
    optionsArray.forEach(option => {
        machineInput.list.appendChild(option);
    });
}

function updateOperatorDatalist(event) {
    const machineValue = event.target.value || null;
    const operatorInput = event.target.closest("tr").querySelector(".operator");
    operatorInput.list.innerHTML = "";
    let operatorData = JSON.parse(localStorage.getItem("OperatorOccupancyData")) || {};
    // Create an array to store option elements
    let optionsArray = [];
    if (operatorOptions[machineValue]) {
        operatorOptions[machineValue].forEach(operator => {
            let operatorOccupancy = operatorData[operator] || [];  // Get the occupancy data for the specific machine
            // Find the maximum end date
            let maxEndDate = null;
            let formattedDate = formatDateWithCustomLocale(Date.now());

            operatorOccupancy.forEach(occupancy => {
                let endDate = new Date(occupancy.end);  // Convert to Date object
                if (!maxEndDate || endDate > maxEndDate) {
                    maxEndDate = endDate;  // Update maxEndDate if the current endDate is later
                }
                if (maxEndDate > Date.now()) {
                    formattedDate = formatDateWithCustomLocale(maxEndDate);
                    return formattedDate;
                }
            });
            let option = document.createElement("option");
            option.value = operator;
            option.textContent = `Available from: ${formattedDate}`;  // Display the formatted date in the option text
            // operatorInput.list.appendChild(option);
            // Add the option to the optionsArray
            // Store the maxEndDate as a timestamp in a data attribute
            option.setAttribute("data-end", maxEndDate ? maxEndDate.getTime() : Date.now());

            // Add the option to the optionsArray
            optionsArray.push(option);
        });
    }
    // Sort the options based on the data-end attribute (ascending order)
    optionsArray.sort((a, b) => {
        let aDate = parseInt(a.getAttribute("data-end"), 10);  // Get the timestamp from the data-end attribute
        let bDate = parseInt(b.getAttribute("data-end"), 10);  // Get the timestamp from the data-end attribute
        return aDate - bDate;  // Sort in ascending order
    });

    // Append all sorted options to the input field
    optionsArray.forEach(option => {
        operatorInput.list.appendChild(option);
    });
}

function formatDateWithCustomLocale(dateStr) {
    const date = new Date(dateStr);
  
    const options = {
      weekday: 'short',   // 'short' is optional; you can remove it if you don't want the weekday name
      year: 'numeric',
      month: '2-digit',   // '2-digit' ensures the month and day are always two digits
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: true        // Ensures 12-hour format with AM/PM
    };
  
    // Format using toLocaleString and specify the 'en-GB' locale for DD/MM/YYYY format
    return date.toLocaleString('en-GB', options).replace(',', '').replace(/\//g, '/');
}

document.addEventListener("DOMContentLoaded", function () {

    productTypeInput.addEventListener("input", updateProcessDatalist);
    // productTable.addEventListener("input", updateProcessDatalist);

    // Add event listeners to the table rows
    // document.querySelector('.rc-table tbody').addEventListener('input', (event) => {
    //     if (event.target.classList.contains('process')) {
    //         updateProcessDatalist();
    //         updateMachineDatalist(event);
    //     } else if (event.target.classList.contains('machine')) {
    //         updateOperatorDatalist(event);
    //     }
    // });


    document.addEventListener("input", function (event) {
        if (event.target.classList.contains("process")) {
            updateMachineDatalist(event);
        } else if (event.target.classList.contains("machine")) {
            updateOperatorDatalist(event);
        }
    });

    document.querySelectorAll(".process").forEach(input => {
        let dataList = document.createElement("datalist");
        dataList.id = input.name + "-list";
        input.setAttribute("list", dataList.id);
        document.body.appendChild(dataList);
    });

    document.querySelectorAll(".machine").forEach(input => {
        let dataList = document.createElement("datalist");
        dataList.id = input.name + "-list";
        input.setAttribute("list", dataList.id);
        document.body.appendChild(dataList);
    });

    document.querySelectorAll(".operator").forEach(input => {
        let dataList = document.createElement("datalist");
        dataList.id = input.name + "-list";
        input.setAttribute("list", dataList.id);
        document.body.appendChild(dataList);
    });
});

// ---------------------------------------------------------------------------------------------------------------------------------------------

console.log('RCdata',JSON.parse(localStorage.getItem('rcDataList')));

// localStorage.removeItem('rcDataList');
// localStorage.removeItem('TaskData');
// localStorage.removeItem('MachineOccupancyData');
// localStorage.removeItem('OperatorOccupancyData');
// localStorage.removeItem('PlannedProjectsData');

console.log('TaskData',JSON.parse(localStorage.getItem('TaskData')));
console.log('MachineOccupancyData',JSON.parse(localStorage.getItem('MachineOccupancyData')));
console.log('OperatorOccupancyData',JSON.parse(localStorage.getItem('OperatorOccupancyData')));
console.log('PlannedProjectsData',JSON.parse(localStorage.getItem('PlannedProjectsData')));


routeCardData = JSON.parse(localStorage.getItem('rcDataList')) || [];

// for (let n in routeCardData) {
//     scheduleTasks(routeCardData[n]);
// }

// Function to schedule tasks based on route card data
function scheduleTasks(routeCardData) {
    let machineData = JSON.parse(localStorage.getItem("MachineOccupancyData")) || {};
    let operatorData = JSON.parse(localStorage.getItem("OperatorOccupancyData")) || {};
    let plannedProjects = JSON.parse(localStorage.getItem("PlannedProjectsData")) || {};
    let taskData = JSON.parse(localStorage.getItem("TaskData")) || {};

    if (!localStorage.getItem("MachineOccupancyData")) localStorage.setItem("MachineOccupancyData", JSON.stringify({}));
    if (!localStorage.getItem("OperatorOccupancyData")) localStorage.setItem("OperatorOccupancyData", JSON.stringify({}));
    if (!localStorage.getItem("TaskData")) localStorage.setItem("TaskData", JSON.stringify({}));
    if (!localStorage.getItem("PlannedProjectsData")) localStorage.setItem("PlannedProjectsData", JSON.stringify({}));

    if (!routeCardData) return;
    if (!routeCardData.productProcesses) return;
    if (!routeCardData.rcId) return;
    if (routeCardData.rcId){
        for (let n in plannedProjects) {
            if (plannedProjects[n].rcId === routeCardData.rcId) {
                return;
            }
        }
    }

    let currentIST = new Date(routeCardData.projectStart);
    // Adjusting the start time based on your shift hours
    if (currentIST.getHours() < 9 || (currentIST.getHours() === 9 && currentIST.getMinutes() < 30)) {
        currentIST.setHours(9, 30, 0, 0);
    } else if (currentIST.getHours() >= 18 || (currentIST.getHours() === 18 && currentIST.getMinutes() > 30)) {
        currentIST.setDate(currentIST.getDate() + 1);
        currentIST.setHours(9, 30, 0, 0);
    }

    let projectId = routeCardData.rcId;
    plannedProjects[projectId] = { rcId: projectId, productProcesses: {} };

    let lastEndTime = currentIST;
    let i = 1;
    let newData = {};
    for (let processId in routeCardData.productProcesses) {
        let currentProcess = routeCardData.productProcesses[processId];
        let {process, machine, operator, ctHours, ctMinutes, source} = currentProcess;

        let description = `${projectId} - ${process}`;
        let startTime;
        slno = projectId + "-" + i;
        if (source === "Outsourced") {
            startTime = lastEndTime;
        }else if (!machine && !operator) {
            startTime = lastEndTime;
        }else{
            startTime = findNextAvailableSlot(machine, operator, lastEndTime, machineData, operatorData, ctHours, ctMinutes);
        }
        let endTime = calculateEndTime(startTime, ctHours, ctMinutes);
        // taskData[processId] = {...currentProcess, startDate: startTime, endDate: endTime };
        plannedProjects[projectId].productProcesses[processId] = {slno,...currentProcess, startDate: startTime, endDate: endTime};
        newData[i] = {slno, ...currentProcess, startDate: startTime, endDate: endTime };
        // taskData.push(taskData[processId]);

        updateOccupancy(machineData, operatorData, machine, operator, startTime, endTime, slno);
        i++;
        lastEndTime = endTime;
    }
    taskData[projectId] = { ...newData };

    localStorage.setItem("TaskData", JSON.stringify(taskData));
    localStorage.setItem("PlannedProjectsData", JSON.stringify(plannedProjects));
    localStorage.setItem("MachineOccupancyData", JSON.stringify(machineData));
    localStorage.setItem("OperatorOccupancyData", JSON.stringify(operatorData));
}

function findNextAvailableSlot(machine, operator, currentIST, machineData, operatorData, ctHours, ctMinutes) {
    let checkTime = new Date(currentIST);
    let taskDuration = (ctHours * 60 + ctMinutes) * 60000; // Total task length in milliseconds

    // Function to check if the machine and operator are both available
    function isAvailableAtTime(checkTime) {
        let machineAvailable = isAvailable(machine, checkTime, machineData);
        let operatorAvailable = isAvailable(operator, checkTime, operatorData);
        return machineAvailable && operatorAvailable;
    }

    while (true) {
        // Check if the machine and operator are available for the entire task length
        if (isAvailableAtTime(checkTime)) {
            return checkTime;  // If both are available, return the current checkTime
        }

        // Find the next available slot by checking the end time of the conflicting task
        let conflictEndTime = findEndOfConflictingTask(checkTime, machine, operator, machineData, operatorData, taskDuration);

        // Adjust checkTime to the end of the conflicting task
        checkTime = new Date(conflictEndTime.getTime()); // Set checkTime to the end of the conflicting task
        
        // Ensure checkTime is within working hours and is not on Sunday
        ensureWorkingHoursAndNotSunday(checkTime);
    }
}

// Function to find the end time of a conflicting task
function findEndOfConflictingTask(checkTime, machine, operator, machineData, operatorData, taskDuration) {
    let conflictingTasks = findConflictingTasks(checkTime, machine, operator, machineData, operatorData, taskDuration);
    let conflictEndTime = checkTime;

    if (conflictingTasks.length > 0) {
        // Get the latest task's end time from the conflicting tasks
        conflictEndTime = new Date(Math.max(...conflictingTasks.map(task => new Date(task.end))));
    }

    return conflictEndTime;
}
// Function to find tasks that overlap with the checkTime
function findConflictingTasks(checkTime, machine, operator, machineData, operatorData) {
    let machineConflicts = machineData[machine]?.filter(task => {
        let taskStart = new Date(task.start);
        let taskEnd = new Date(task.end);
        return checkTime >= taskStart && checkTime < taskEnd;
    }) || [];

    let operatorConflicts = operatorData[operator]?.filter(task => {
        let taskStart = new Date(task.start);
        let taskEnd = new Date(task.end);
        return checkTime >= taskStart && checkTime < taskEnd;
    }) || [];

    // Combine both machine and operator conflicts
    return [...machineConflicts, ...operatorConflicts];
}

// function findConflictingTasks(checkTime, machine, operator, machineData, operatorData, taskDuration) {
//     let machineConflicts = machineData[machine]?.filter(task => {
//         let taskStart = new Date(task.start);
//         let taskEnd = new Date(task.end);
//         // Check if the new task (from checkTime to checkTime + taskDuration) overlaps with the current task
//         return (
//             (checkTime < taskEnd && new Date(checkTime.getTime() + taskDuration) > taskStart)
//         );
//     }) || [];

//     let operatorConflicts = operatorData[operator]?.filter(task => {
//         let taskStart = new Date(task.start);
//         let taskEnd = new Date(task.end);
//         // Check if the new task (from checkTime to checkTime + taskDuration) overlaps with the current task
//         return (
//             (checkTime < taskEnd && new Date(checkTime.getTime() + taskDuration) > taskStart)
//         );
//     }) || [];

//     // Combine both machine and operator conflicts
//     return [...machineConflicts, ...operatorConflicts];
// }


// Function to ensure that checkTime respects working hours and is not on a Sunday
function ensureWorkingHoursAndNotSunday(checkTime) {
    // Working hours: 09:30 AM to 06:30 PM
    if (checkTime.getHours() >= 18 || (checkTime.getHours() === 18 && checkTime.getMinutes() > 30)) {
        checkTime.setDate(checkTime.getDate() + 1);  // Move to the next day
        checkTime.setHours(9, 30, 0, 0);  // Set to 09:30 AM
    }

    // Check if the current day is Sunday
    if (checkTime.getDay() === 0) {  // 0 is Sunday
        checkTime.setDate(checkTime.getDate() + 1);  // Move to Monday
        checkTime.setHours(9, 30, 0, 0);  // Set to 09:30 AM
    }
}

function isAvailable(resource, checkTime, occupancyData) {
    if (!occupancyData[resource]) return true;
    return !occupancyData[resource].some(slot => checkTime >= new Date(slot.start) && checkTime < new Date(slot.end));
}
// Function to calculate end time based on working hours, excluding Sundays
function calculateEndTime(startDate, ctHours, ctMinutes) {
    let workStart = new Date();
    workStart.setHours(9, 30, 0, 0); // 9:30 AM

    let workEnd = new Date();
    workEnd.setHours(18, 30, 0, 0); // 6:30 PM

    let start = new Date(startDate);
    let totalMinutes = parseInt(ctHours) * 60 + parseInt(ctMinutes);

    while (totalMinutes > 0) {
        let currentMinutes = start.getHours() * 60 + start.getMinutes();
        let remainingWorkDay = (workEnd.getHours() * 60 + workEnd.getMinutes()) - currentMinutes;

        if (remainingWorkDay >= totalMinutes) {
            start.setMinutes(start.getMinutes() + totalMinutes);
            totalMinutes = 0;
        } else {
            totalMinutes -= remainingWorkDay;
            start.setDate(start.getDate() + 1);
            start.setHours(9, 30, 0, 0);

            // Skip Sundays by checking the day and moving to Monday if it's Sunday
            if (start.getDay() === 0) {
                start.setDate(start.getDate() + 1);
                start.setHours(9, 30, 0, 0);
            }
        }
    }
    return start;
}

function updateOccupancy(machineData, operatorData, machine, operator, startTime, endTime, slno) {
    
    if (!machine || !operator) return;

    if (!machineData[machine]) machineData[machine] = [];
    if (!operatorData[operator]) operatorData[operator] = [];
    machineData[machine].push({ slno, start: startTime, end: endTime });
    operatorData[operator].push({slno, start: startTime, end: endTime });
}
