// Retrieve the RFQ data from session storage
const currentRFQId = sessionStorage.getItem('currentRFQId');

console.log(currentRFQId);

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

    // localStorage.removeItem('rfqDataList');
    // localStorage.removeItem('rawMaterials');

    document.getElementById('rfqNo').value = await generateRFQId();

    // Get today's date and format it (YYYY-MM-DD)
    const today = new Date();
    const formattedDate = formatDate(today);

    // document.getElementById('receiveDate').value = formattedDate;
    document.getElementById('rfqDate').value = formattedDate;

    try {
        const response = await fetch('/api/v1/customers');
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const companyData = await response.json();
        const companyNameSelect = document.getElementById("customer");

        companyData.forEach(company => {
            const companyId1 = company.companyId1;
            if (companyId1 && (companyId1.startsWith('UEPL/CUS/') || companyId1.startsWith('UEPL/CV/') || companyId1.startsWith('UEPL/VEN/'))) {
                const option = document.createElement("option");
                option.value = company.companyName;
                option.textContent = company.companyName;
                companyNameSelect.appendChild(option);
            }
        });
    } catch (error) {
        console.error("Error fetching company data:", error);
    }

    if (currentRFQId) {
        // Fetch customer data by companyId
        const response = await fetch(`/api/v1/rfqs/${currentRFQId}`);
        const currentRFQ = await response.json();

        if (currentRFQ) {
            // Populate the form fields with the RFQ data
            document.getElementById("rfqNo").value = currentRFQ.rfqNo || '';
            document.getElementById("rfqDate").value = currentRFQ.rfqDate || '';
            document.getElementById("cusRefNo").value = currentRFQ.cusRefNo || '';
            document.getElementById("customer").value = currentRFQ.customer || '';
            document.getElementById("partNo").value = currentRFQ.partNo || '';
            document.getElementById("project-materialNo").value = currentRFQ.projectMaterialNo || '';
            document.getElementById("drawingNo").value = currentRFQ.drawingNo || '';
            document.getElementById("drawingRev").value = currentRFQ.drawingRev || '';
            document.getElementById("quantity").value = currentRFQ.quantity || '';
            document.getElementById("uom").value = currentRFQ.uom || '';
            document.getElementById("note").value = currentRFQ.note || '';
            document.getElementById('drawingFile').value = currentRFQ.drawingFile || '';
            
             // Handle rfqType
            const rfqTypeElement = document.getElementById('rfqType');
            const otherRfqInputElement = document.getElementById('other-rfq-input');
            const otherRfqTypeElement = document.getElementById('other-rfq-type');

            // Check if currentRFQ.rfqType matches the available options
            const rfqTypeExists = Array.from(rfqTypeElement.options).some(option => option.value === currentRFQ.rfqType);

            if (!rfqTypeExists || currentRFQ.rfqType === 'Other') {
                rfqTypeElement.value = 'Other';
                otherRfqInputElement.style.display = 'block';
                otherRfqTypeElement.value = currentRFQ.rfqType || '';
            } else {
                rfqTypeElement.value = currentRFQ.rfqType;
            }

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

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

            if (!productTypeExists || currentRFQ.productType === 'other') {
                productTypeElement.value = 'other';
                otherProductInputElement.style.display = 'block';
                otherProductTypeElement.value = currentRFQ.productType || '';
            } else {
                productTypeElement.value = currentRFQ.productType;
            }
            const rawMaterials = currentRFQ.rawMaterials || [];
            populateExistingRawMaterials(rawMaterials);
            
            document.getElementById('drawingFile').removeAttribute('required');


        }
    }
    else {
        // Populate raw materials on page load
        const rawMaterialsDropdowns = document.querySelectorAll('select[name="rawmaterial"]');
        rawMaterialsDropdowns.forEach(populateRawMaterialDropdown);
    }
    /**
     * -----------------------------Start of the script for material fields generation-------------------------------------------------------------------
     */

    // Event listener for the add-material button click
    document.querySelector('.add-materials').addEventListener('click', function (event) {
        event.preventDefault();
        addMaterialRow();
    });

    // Event delegation for handling remove button clicks
    document.getElementById('additionalFields').addEventListener('click', function (event) {
        if (event.target.closest('.remove-material')) {
            event.preventDefault();

            // Remove the entire row containing the material and quantity fields
            const rowToRemove = event.target.closest('.material-row');
            if (rowToRemove) {
                rowToRemove.remove();
            }
        }
    });

    //functionality to add a new raw material via a popup
    const materialDropdown = document.getElementById('rawmaterial');
    const addRawMaterialForm = document.getElementById('addRawMaterialForm');

    // Open modal when "Add Raw Material" is selected
    // materialDropdown.addEventListener('change', function () {
    //     if (materialDropdown.value === 'new') {
    //         $('#addRawMaterialModal').modal('show'); // Bootstrap modal
    //  

    // Add new raw material to the dropdown and local storage
    addRawMaterialForm.addEventListener('submit', async function (event) {
        event.preventDefault();

        // Collect raw material data from form fields
        const newRawMaterialName = document.getElementById('newRawMaterialName').value.trim();
        const isoSpecification = document.getElementById('isoSpecification').value.trim();
        const rmDensity = document.getElementById('rmDensity').value.trim();
        const mechanicalProperties = document.getElementById('mechanicalProperties').value.trim();
        const chemicalProperties = document.getElementById('chemicalProperties').value.trim();

        if (newRawMaterialName && rmDensity) {
            // Prepare data object
            const rawMaterialData = {
                name: newRawMaterialName,
                isoSpecification,
                rmDensity,
                mechanicalProperties,
                chemicalProperties
            };

            try {
                // Send data to API
                const response = await fetch("/api/v1/raw-materials", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify(rawMaterialData)
                });

                if (!response.ok) {
                    throw new Error("Failed to add raw material");
                }

                // Fetch updated list of raw materials
                const updatedRawMaterial = await response.json();

                // Get all dropdowns for raw materials
                const allDropdowns = document.querySelectorAll('select[name="rawmaterial"]');

                // Re-populate all dropdowns with the updated list
                allDropdowns.forEach(dropdown => populateRawMaterialDropdown(dropdown));

                // Reset the form fields and close the modal
                addRawMaterialForm.reset();
                $('#addRawMaterialModal').modal('hide');

                alert('New raw material added successfully!');
            } catch (error) {
                console.error("Error:", error);
                alert('Error adding raw material. Please try again.');
            }
        } else {
            alert('Please fill in required fields!');
        }
    });
    sessionStorage.removeItem('currentRFQId');
});

// Handle form submission
document.getElementById('rfqform').addEventListener('submit', async function (event) {
    event.preventDefault(); // Prevent default form submission

    // Collect form data
    const rfqNo = document.getElementById("rfqNo").value.trim() || null;
    const rfqDate = document.getElementById("rfqDate").value || null;
    const cusRefNo = document.getElementById("cusRefNo").value.trim() || null;
    const customer = document.getElementById("customer").value.trim() || null;
    const rfqType = document.getElementById("rfqType").value.trim() || null;
    const otherRfqType = document.getElementById("other-rfq-type").value.trim() || null;
    const productType = document.getElementById("productType").value.trim() || null;
    const otherProductType = document.getElementById("other-product-type").value.trim() || null;
    const partNo = document.getElementById("partNo").value.trim() || null;
    const projectMaterialNo = document.getElementById("project-materialNo").value.trim() || null;
    const drawingNo = document.getElementById("drawingNo").value.trim() || null;
    const drawingRev = document.getElementById("drawingRev").value.trim() || null;
    const quantity = document.getElementById("quantity").value || null;
    const uom = document.getElementById("uom").value.trim() || null;
    const note = document.getElementById("note").value.trim() || null;

    // Collect raw materials
    const rawMaterials = [];
    document.querySelectorAll('#additionalFields .material-row').forEach(row => {
        const rawMaterial = row.querySelector('select[name="rawmaterial"]').value.trim();
        if (rawMaterial) rawMaterials.push({ name: rawMaterial });
    });

    // File inputs
    const drawingFile = document.getElementById("drawingFile").files[0];
    const materialSpecificationFile = document.getElementById("material-specificationFile").files[0];
    const rfqFormFile = document.getElementById("rfqformFile").files[0];
    const annexureFile = document.getElementById("annexureFile").files[0];

    // Validate required fields
    if (!rfqNo || !rfqDate || !customer || !rfqType || !productType || !partNo || !projectMaterialNo || !drawingNo || !quantity || !uom) {
        alert("Please fill in all required fields.");
        return;
    }

    // Determine final RFQ Type and Product Type
    const finalRfqType = rfqType === 'other' ? otherRfqType : rfqType;
    const finalProductType = productType === 'other' ? otherProductType : productType;

    // Convert files to Base64
    async function fileToBase64(file) {
        return new Promise((resolve, reject) => {
            if (!file) return resolve(null);
            const reader = new FileReader();
            reader.onload = (event) => resolve(event.target.result.split(',')[1]); // Get only the Base64 content
            reader.onerror = (error) => reject(error);
            reader.readAsDataURL(file);
        });
    }

    try {
        const [drawingBase64, materialSpecBase64, rfqFormBase64, annexureBase64] = await Promise.all([
            fileToBase64(drawingFile),
            fileToBase64(materialSpecificationFile),
            fileToBase64(rfqFormFile),
            fileToBase64(annexureFile)
        ]);

        // Prepare files array (each file should be an object inside the `files` array)
        // const files = [];
        // if (drawingBase64) files.push({ drawingFile: `data:image/png;base64,${drawingBase64}` });
        // if (materialSpecBase64) files.push({ materialSpecificationFile: `data:application/pdf;base64,${materialSpecBase64}` });
        // if (rfqFormBase64) files.push({ rfqFormFile: `data:application/pdf;base64,${rfqFormBase64}` });
        // if (annexureBase64) files.push({ annexureFile: `data:application/pdf;base64,${annexureBase64}` });

        const files = {};

        if (drawingBase64) files.drawingFile = `data:application/pdf;base64,${drawingBase64}`;
        if (materialSpecBase64) files.materialSpecificationFile = `data:application/pdf;base64,${materialSpecBase64}`;
        if (rfqFormBase64) files.rfqFormFile = `data:application/pdf;base64,${rfqFormBase64}`;
        if (annexureBase64) files.annexureFile = `data:application/pdf;base64,${annexureBase64}`;


        // Prepare the form data object
        const formData = {
            rfqNo,
            rfqDate,
            cusRefNo,
            customer,
            rfqType: finalRfqType,
            productType: finalProductType,
            partNo,
            projectMaterialNo,
            drawingNo,
            drawingRev,
            quantity,
            uom,
            note,
            rawMaterials,
            files
        };

        // Debugging: Print formData before sending request
        console.log("RFQ Data:", JSON.stringify(formData, null, 2));

        let response;

        if (typeof currentRFQId !== "undefined" && currentRFQId) {
            const response1 = await fetch(`/api/v1/rfqs/${currentRFQId}`);
            const edit = await response1.json();
            const userConfirmation = confirm(`A RFQ with this ID ${edit.rfqNo} already exists. Do you want to override it?`);
            if (userConfirmation) {
                response = await fetch(`/api/v1/rfqs/${currentRFQId}/`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData)
                });
                alert("RFQ data has been updated successfully.");
            } else {
                alert("The data was not saved.");
                return;
            }
            if (!response.ok) throw new Error(`Failed to update RFQ: ${response.statusText}`);

        } else {
            response = await fetch("/api/v1/rfqs/", {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            if (!response.ok) {
                const errorResponse = await response.json();
                console.error("Server response error:", errorResponse);
                throw new Error(`Failed to save RFQ data: ${JSON.stringify(errorResponse)}`);
            } else {
                alert("RFQ form submitted successfully!");
            }
        }
        document.getElementById('rfqform').reset();
        sessionStorage.removeItem('currentRFQId'); // Clear session storage
        window.location.href = 'rfq-datatable.html'; // Replace with your desired URL
    } catch (error) {
        console.error("Error during API request:", error);
        alert(`An error occurred: ${error.message}`);
    }
});

// Function to generate the RFQ ID using API data
async function generateRFQId() {
    try {
        const response = await fetch('/api/v1/rfqs/');
        if (!response.ok) {
            throw new Error(`Failed to fetch RFQ data: ${response.statusText}`);
        }
        const rfqDataList = await response.json();

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

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

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

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


// Function to format the date as yyyy-mm-dd
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // Add leading zero for single-digit months
    const day = String(date.getDate()).padStart(2, '0'); // Add leading zero for single-digit days
    return `${year}-${month}-${day}`; // Return in YYYY-MM-DD format
}

// Helper function to set the select field based on option text
function setSelectValueByText(selectId, textValue) {
    const selectElement = document.getElementById(selectId);
    if (selectElement) {
        const matchedOption = [...selectElement.options].find(option => option.text === textValue);
        selectElement.value = matchedOption ? matchedOption.value : ''; // Set matched option or reset if not found
    }
}

// Function to toggle customer input and redirect if "New" is selected
function toggleCustomerInput() {
    var select = document.getElementById('customer');
    var selectedValue = select.value;

    if (selectedValue === 'New') {
        // Redirect to the new customer page
        window.location.href = 'customer-details.html'; // Replace with your desired URL
    }
}

// Show/Hide "Other" Input Fields
document.getElementById("rfqType").addEventListener("change", function () {
    const otherInput = document.getElementById("other-rfq-input");
    otherInput.style.display = this.value === "Other" ? "block" : "none";
});

document.getElementById("productType").addEventListener("change", function () {
    const otherInput = document.getElementById("other-product-input");
    otherInput.style.display = this.value === "Other" ? "block" : "none";
});
//----------------------------------------------------------------------------------------------
// Define the density values for the materials
const materialDensities = {
    "Iron": "7800",     // Density in kg/m³
    "Steel": "7850",
    "Aluminum": "2700",
    "Brass": "8500",
    "Bronze": "8700",
    "Plastic": "1200"
};

// Add event listener to the 'Raw Material Name' input field
document.getElementById('newRawMaterialName').addEventListener('input', function () {
    const materialName = this.value.trim();
    const densityField = document.getElementById('rmDensity');

    // Check if the entered value matches any material and update the density field
    if (materialDensities[materialName]) {
        densityField.value = materialDensities[materialName];
    } else {
        densityField.value = '';  // Clear if no match
    }
});

function materialPopup() {
    const materialDropdown = document.getElementById('rawmaterial');
    if (materialDropdown.value === 'new') {
        $('#addRawMaterialModal').modal('show'); // Bootstrap modal
    }
}

// Function to populate dropdown options with raw materials
async function populateRawMaterialDropdown(dropdown) {
    try {
        const response = await fetch('/api/v1/raw-materials');
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const rawMaterials = await response.json();

        // Clear existing options except the default ones
        dropdown.innerHTML = `
            <option value="" disabled>Raw Material Name</option>
            <option value="new">Add Raw Material</option>
        `;

        // Add raw materials to the dropdown
        rawMaterials.forEach(material => {
            if (material.name) { // Ensure material has a valid name
                const option = document.createElement('option');
                option.value = material.isoSpecification.replace(/\s+/g, '-') + '-' + material.name.replace(/\s+/g, '-'); // Use a slug-like value
                option.textContent = `${material.isoSpecification || ''} -  ${material.name}`;
                dropdown.insertBefore(option, dropdown.querySelector('option[value="new"]'));
            }
        });
    } catch (error) {
        console.error("Error populating dropdown:", error);
    }
}

// Function to add a new row of material fields
function addMaterialRow() {
    // Create a new row container for the new fields
    const newRow = document.createElement('div');
    newRow.classList.add('row', 'material-row');

    // Create the Material input field
    const materialCol = document.createElement('div');
    materialCol.classList.add('col-md-10');
    materialCol.innerHTML = `
        <div class="form-group">
            <label for="material">Raw Material</label>
            <select id="rawmaterial" name="rawmaterial" required></select><br><br>
        </div>
    `;

    // Populate the dropdown with current raw materials
    const dropdown = materialCol.querySelector('select');
    populateRawMaterialDropdown(dropdown);

    // Open the "Add Raw Material" modal when the "Add Raw Material" option is selected
    dropdown.addEventListener('change', function () {
        if (dropdown.value === 'new') {
            $('#addRawMaterialModal').modal('show'); // Bootstrap modal
        }
    });

    // Create the delete button with the fa-times-circle icon
    const deleteButtonCol = document.createElement('div');
    deleteButtonCol.classList.add('col-md-2');
    deleteButtonCol.innerHTML = `
        <button type="button" class="btn btn-danger remove-material"><i class="fas fa-times-circle"></i></button>
    `;

    // Append the input fields and delete button to the new row
    newRow.appendChild(materialCol);
    newRow.appendChild(deleteButtonCol);

    // Insert the new row at the bottom of the additionalFields container
    const additionalFieldsContainer = document.getElementById('additionalFields');
    additionalFieldsContainer.appendChild(newRow);

    // Add delete functionality for the newly created row
    deleteButtonCol.querySelector('.remove-material').addEventListener('click', function () {
        newRow.remove();
    });
}

// Function to pre-populate all raw material rows based on existing data (from currentRFQ.rawMaterials)
async function populateExistingRawMaterials(rawMaterials) {
    const additionalFieldsContainer = document.getElementById('additionalFields');
    additionalFieldsContainer.innerHTML = ''; // Clear existing rows

    // Assuming rawMaterials is an array of objects with a 'name' property
    for (const material of rawMaterials) {
        const newRow = document.createElement('div');
        newRow.classList.add('row', 'material-row');

        const materialCol = document.createElement('div');
        materialCol.classList.add('col-md-10');
        materialCol.innerHTML = `
            <div class="form-group">
                <label for="material">Raw Material</label>
                <select class="rawmaterial" name="rawmaterial" required>
                    <option value="">Select Raw Material</option>
                    <option value="new">Add Raw Material</option>
                </select><br><br>
            </div>
        `;

        const dropdown = materialCol.querySelector('select');

        // Populate the dropdown with available raw materials
        await populateRawMaterialDropdown(dropdown);

        // Set the selected value for this material
        const selectedMaterial = material.name || 'new'; // Fallback to 'new' if material.name is undefined

        // Debugging log
        console.log("Trying to select material:", selectedMaterial);
        console.log("Dropdown options:", Array.from(dropdown.options).map(option => option.value));

        // Set the selected value only after the dropdown is populated
        dropdown.value = selectedMaterial;

        // If the selected material is not found, set it to "new"
        if (!Array.from(dropdown.options).some(option => option.value === selectedMaterial)) {
            dropdown.value = 'new';  // Fallback to "Add Raw Material" if not found
        }

        const deleteButtonCol = document.createElement('div');
        deleteButtonCol.classList.add('col-md-2');
        deleteButtonCol.innerHTML = `
            <button type="button" class="btn btn-danger remove-material"><i class="fas fa-times-circle"></i></button>
        `;

        newRow.appendChild(materialCol);
        newRow.appendChild(deleteButtonCol);

        // Append the new row to the additional fields container
        additionalFieldsContainer.appendChild(newRow);

        // Add delete functionality for the newly created row
        deleteButtonCol.querySelector('.remove-material').addEventListener('click', function () {
            newRow.remove();
        });
    }
}
