
function printReceipt(salesId) {
    window.open("print_receipt.php?sales_id=" + salesId, "_blank");
}

function addRow() {
    let table = document.getElementById("productTable");
    let row = table.insertRow(-1);
    row.innerHTML = `
        <td>
            <select name="product_name[]" onchange="setProductDetails(this)" required>
                <option value="">Select Product</option>
                <?php echo getProductDropdown($conn); ?>
            </select>
        </td>
        <td><input type="text" name="product_description[]" required></td>
        <td><input type="number" name="quantity[]" min="1" value="1" onchange="updateTotal(this)" required></td>
        <td><input type="number" name="price[]" min="0" step="0.01" onchange="updateTotal(this)" required></td>
        <td><input type="text" name="total[]" readonly></td>
        <td>
            <button type="button" onclick="addRow()" class="action-button">Add</button>
            <button type="button" onclick="removeRow(this)" class="remove-button">Remove</button>
        </td>
    `;
}

function removeRow(button) {
    let table = document.getElementById("productTable");
    if (table.rows.length > 2) { // Prevent removing the last remaining row
        button.parentElement.parentElement.remove();
        updateGrandTotal();
    } else {
        alert("You must have at least one product row.");
    }
}

function updateTotal(input) {
    let row = input.parentElement.parentElement;
    let quantity = row.querySelector('[name="quantity[]"]').value;
    let price = row.querySelector('[name="price[]"]').value;
    let total = row.querySelector('[name="total[]"]');
    total.value = (quantity * price).toFixed(2);
    updateGrandTotal();
}

function updateGrandTotal() {
    let totals = document.querySelectorAll('[name="total[]"]');
    let grandTotal = 0;
    totals.forEach(total => {
        if (total.value) {
            grandTotal += parseFloat(total.value);
        }
    });

    let discount = parseFloat(document.getElementById("discount").value) || 0;
    let deposit = parseFloat(document.getElementById("deposit").value) || 0;

    grandTotal = grandTotal - discount - deposit;
    document.getElementById("grandTotal").innerText = grandTotal.toFixed(2);
}

function setProductDetails(select) {
    let row = select.parentElement.parentElement;
    let selectedOption = select.options[select.selectedIndex];
    let price = selectedOption.getAttribute('data-price');
    let description = selectedOption.getAttribute('data-description');
    row.querySelector('[name="product_description[]"]').value = description;
    row.querySelector('[name="price[]"]').value = price;
    updateTotal(row.querySelector('[name="quantity[]"]')); // Update total on change
}
