function addSelectedProduct() {
    const productSelect = document.getElementById("productSelect");
    const selectedOption = productSelect.options[productSelect.selectedIndex];

    const product = {
        id: selectedOption.value,
        description: selectedOption.getAttribute("data-description"),
        price: parseFloat(selectedOption.getAttribute("data-price")),
        purchase_price: parseFloat(selectedOption.getAttribute("data-purchase_price")),
    };

    addProductToList(product);
}

function addProductToList(product) {
    const table = document.getElementById("productList");
    const row = table.insertRow();
    row.innerHTML = `
        <td><input type="hidden" name="product_id[]" value="${product.id}">${product.id}</td>
        <td><input type="hidden" name="product_description[]" value="${product.description}">${product.description}</td>
        <td><input type="number" name="quantity[]" value="1" min="1" onchange="updateTotal(this)"></td>
        <td><input type="hidden" name="price[]" value="${product.price}">${product.price.toFixed(2)}</td>
        <td class="total">${product.price.toFixed(2)}</td>
        <td><button type="button" class="btn btn-danger" onclick="removeProduct(this)">Remove</button></td>
    `;
    calculateGrandTotal();
}

function removeProduct(button) {
    button.closest("tr").remove();
    calculateGrandTotal();
}

function calculateGrandTotal() {
    let grandTotal = 0;
    document.querySelectorAll(".total").forEach(td => {
        grandTotal += parseFloat(td.innerText);
    });
    document.getElementById("grand_total").value = grandTotal.toFixed(2);
}
