

        // JavaScript Document

        function refreshPage() {
            location.reload();
        }

        // Show QR Modal
        function showQRModal() {
            $('#qrModal').modal('show');
        }

        function popProduct() {
            // Perform actions to add product here

            // Close the modal
            $('#exampleModal').modal('hide');
        }
        function toggleSubMenu(element) {
            var submenu = element.nextElementSibling;
            submenu.style.display = (submenu.style.display === "block") ? "none" : "block";
        }

        // Declare discountAmount variable globally
        let discountAmount = 0;

        // Declare discountInput globally
        const discountInput = document.getElementById('discount-input');

        // Function to filter products by category
        function filterProductsByCategory(category) {
            // Select all product cards
            const products = document.querySelectorAll('.product-card');
            // Loop through each product card
            products.forEach(product => {
                const productCategory = product.getAttribute('data-category');
                // Show or hide product card based on selected category
                if (productCategory === category || category === 'All') {
                    product.style.display = 'block';
                } else {
                    product.style.display = 'none';
                }
            });
        }

        // Declare variables to access DOM elements
        const qrResult = document.getElementById('qr-result');
        const posTableBody = document.getElementById('pos-table-body');
        const submitPosButton = document.getElementById('submit-pos');
		
		const totalAmountDiv = document.getElementById('total-amount');
        let posData = [];

        // Event listener for submitting POS data
        submitPosButton.addEventListener('click', submitPosData);

        // Function to handle file selection
        function handleFileSelect(event) {
            const file = event.target.files[0];
            const reader = new FileReader();
            reader.onload = function (event) {
                const image = new Image();
                image.onload = function () {
                    decodeQRCode(image);
                };
                image.src = event.target.result;
            };
            reader.readAsDataURL(file);
        }

        // Function to decode QR code
        function decodeQRCode(image) {
            // Decode QR code using jsQR library
            const canvasElement = document.createElement('canvas');
            canvasElement.width = image.width;
            canvasElement.height = image.height;
            const canvas = canvasElement.getContext('2d');
            canvas.drawImage(image, 0, 0, canvasElement.width, canvasElement.height);
            const imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
            const code = jsQR(imageData.data, imageData.width, imageData.height, {
                inversionAttempts: "dontInvert",
            });
            // Process decoded QR code
            if (code) {
                qrResult.textContent = code.data;
                const productData = extractProductData(code.data);
                if (productData) {
                    updatePOSTable(productData);
                } else {
                    qrResult.textContent += " - Invalid product data.";
                }
            } else {
                qrResult.textContent = "No QR code found.";
            }
        }

        // Function to extract product data from QR code
        function extractProductData(data) {
            const match = data.match(/Product:\s*(\S+)\s+Price:\s*(\d+(\.\d+)?)/);
            if (match && match.length >= 3) {
                return {
                    productId: generateProductId(), // Generate product ID
                    productName: match[1].trim(),
                    price: parseFloat(match[2])
                };
            } else {
                return null;
            }
        }

        // Function to generate product ID
        function generateProductId() {
            // Generate product ID logic goes here
            // Return the generated product ID
            return "PROD123"; // Example product ID
        }

        // Function to update POS table with product data
        function updatePOSTable(productData) {
            const existingProductIndex = posData.findIndex(item => item.productName === productData.productName);
            if (existingProductIndex !== -1) {
                posData[existingProductIndex].price = productData.price;
                posData[existingProductIndex].quantity++;
            } else {
                productData.quantity = 1;
                posData.push(productData);
            }
            // Calculate and update total amount
            calculateTotalAmount();
            // Render POS table
            renderPOSTable();
        }

        // Function to render POS table
function renderPOSTable() {
    posTableBody.innerHTML = '';
    posData.forEach((item, index) => {
        const row = document.createElement('tr');
        // Calculate the total price for the current item
        //const totalPrice = item.price * item.quantity;
        row.innerHTML = `
            <td>${index + 1}</td>
             <!-- Display product ID -->
            <td class="text-capitalize">${item.productName}</td>
            <td>${item.price}</td>
            <td><input type="number" class="form-control" min="1" value="${item.quantity}" data-index="${index}"></td>
             <!-- Display the calculated total price -->
            <td><button class="btn btn-dark btn-remove" style="border-radius:20px; font-size:7px;" data-index="${index}"><i class="fa fa-trash fa-1x"><i/></button></td>
        `;
        posTableBody.appendChild(row);
    });
}

        // Function to calculate total amount including tax and discount
        function calculateTotalAmount() {
            // Calculate total amount without tax
            let totalAmountWithoutTax = posData.reduce((total, item) => total + (item.price * item.quantity), 0);

            // Calculate total tax amount (assuming tax rate is 10%)
            const totalTaxAmount = totalAmountWithoutTax * 0.10;

            // Calculate total amount including tax
            let totalAmount = totalAmountWithoutTax + totalTaxAmount;

            // Subtract discount amount
            totalAmount -= discountAmount;

            // Update total amount display
            totalAmountDiv.innerHTML = `<h5 style="font-size:12px;">Sub - Total: Rs ${totalAmountWithoutTax.toFixed(2)}</h5>
                                <h6 style="font-size:12px;" id="tax-info">Tax (10%): Rs ${totalTaxAmount.toFixed(2)}</h6>
                                <h6 style="font-size:12px;" id="discount-info">Discount Amount: Rs ${discountAmount.toFixed(2)}</h6>
                                <h6 style="font-size:12px;" id="total-amount-info">Total Amount (incl. tax & discount): Rs ${totalAmount.toFixed(2)}</h6>`;
        }

        // Function to handle discount input
        discountInput.addEventListener('input', function () {
            applyDiscount();
        });

        // Function to apply discount
        function applyDiscount() {
            const discountValue = parseFloat(discountInput.value.trim());
            if (!isNaN(discountValue) && discountValue >= 0) {
                discountAmount = discountValue;
                calculateTotalAmount();
            }
        }

        // Event listener for removing product from POS table
        posTableBody.addEventListener('click', function (event) {
            if (event.target.classList.contains('btn-remove')) {
                const indexToRemove = parseInt(event.target.getAttribute('data-index'));
                posData.splice(indexToRemove, 1);
                renderPOSTable();
                calculateTotalAmount();
            }
        });

        // Event listener for changing quantity in POS table
        posTableBody.addEventListener('input', function (event) {
            if (event.target.tagName === 'INPUT' && event.target.classList.contains('form-control')) {
                const indexToUpdate = parseInt(event.target.getAttribute('data-index'));
                const newQuantity = parseInt(event.target.value);
                if (!isNaN(newQuantity) && newQuantity >= 1) {
                    posData[indexToUpdate].quantity = newQuantity;
                    calculateTotalAmount();
                } else {
                    event.target.value = posData[indexToUpdate].quantity;
                    alert('Please enter a valid quantity.');
                }
            }
        });

        // Function to submit POS data
        function submitPosData() {
            // Create a form element
            const form = document.createElement('form');
            form.setAttribute('method', 'post');
            form.setAttribute('action', 'submit_pos.php'); // Replace 'submit_pos.php' with the actual PHP file to handle the form submission

            // Create input fields for each product in the POS data
            posData.forEach((item, index) => {
                const productIdInput = document.createElement('input');
                productIdInput.setAttribute('type', 'hidden');
                productIdInput.setAttribute('name', `product_id[${index}]`);
                productIdInput.value = item.productId; // Use the product ID from the original database
                form.appendChild(productIdInput);

                const productNameInput = document.createElement('input');
                productNameInput.setAttribute('type', 'hidden');
                productNameInput.setAttribute('name', `product_name[${index}]`);
                productNameInput.value = item.productName;
                form.appendChild(productNameInput);

                const productPriceInput = document.createElement('input');
                productPriceInput.setAttribute('type', 'hidden');
                productPriceInput.setAttribute('name', `product_price[${index}]`);
                productPriceInput.value = item.price;
                form.appendChild(productPriceInput);

                const productQuantityInput = document.createElement('input');
                productQuantityInput.setAttribute('type', 'hidden');
                productQuantityInput.setAttribute('name', `product_quantity[${index}]`);
                productQuantityInput.value = item.quantity;
                form.appendChild(productQuantityInput);
            });

            // Add input fields for total amount, tax, and discount
            const totalAmountInput = document.createElement('input');
            totalAmountInput.setAttribute('type', 'hidden');
            totalAmountInput.setAttribute('name', 'total_amount');
            totalAmountInput.value = totalAmountDiv.innerText;
            form.appendChild(totalAmountInput);

            const totalTaxInput = document.createElement('input');
            totalTaxInput.setAttribute('type', 'hidden');
            totalTaxInput.setAttribute('name', 'total_tax');
            totalTaxInput.value = (parseFloat(totalAmountDiv.innerText) * 0.10).toFixed(2); // Assuming tax rate is 10%
            form.appendChild(totalTaxInput);

            const discountInput = document.createElement('input');
            discountInput.setAttribute('type', 'hidden');
            discountInput.setAttribute('name', 'discount_amount');
            discountInput.value = discountAmount.toFixed(2);
            form.appendChild(discountInput);

            // Add input fields for customer, phone, sale_by, and paid_by
            const customerInput = document.createElement('input');
            customerInput.setAttribute('type', 'hidden');
            customerInput.setAttribute('name', 'customer');
            customerInput.value = document.getElementById('customer-input').value; // Get customer name from input field
            form.appendChild(customerInput);

            const phoneInput = document.createElement('input');
            phoneInput.setAttribute('type', 'hidden');
            phoneInput.setAttribute('name', 'phone');
            phoneInput.value = document.getElementById('phone-input').value; // Get customer phone from input field
            form.appendChild(phoneInput);

            const saleByInput = document.createElement('input');
            saleByInput.setAttribute('type', 'hidden');
            saleByInput.setAttribute('name', 'sale_by');
            saleByInput.value = document.getElementById('sale-by-input').value; // Get sale by information from input field
            form.appendChild(saleByInput);

            const paidByInput = document.createElement('input');
            paidByInput.setAttribute('type', 'hidden');
            paidByInput.setAttribute('name', 'paid_by');
            paidByInput.value = document.getElementById('paid-by-input').value; // Get paid by information from input field
            form.appendChild(paidByInput);

            // Append the form to the document body and submit it
            document.body.appendChild(form);
            form.submit();
        }
		

        // Event listener for manual product addition
        document.getElementById('add-manual-product').addEventListener('click', function () {
            const productName = document.getElementById('manual-product-name').value.trim();
            const productPrice = parseFloat(document.getElementById('manual-product-price').value.trim());
            if (productName && !isNaN(productPrice) && productPrice > 0) {
                const newProduct = {
                    productName: productName,
                    price: productPrice,
                    quantity: 1
                };
                posData.push(newProduct);
                renderPOSTable();
                calculateTotalAmount();
                // Clear input fields
                document.getElementById('manual-product-name').value = '';
                document.getElementById('manual-product-price').value = '';
            } else {
                alert('Please enter a valid product name and price.');
            }
        });

       // Event listener for adding product to POS table using buttons
const addProductButtons = document.querySelectorAll('.add-product');
addProductButtons.forEach(button => {
    button.addEventListener('click', function () {
        const productName = this.getAttribute('data-name');
        const productId = this.getAttribute('data-product-id'); // Retrieve product ID
        const productPrice = parseFloat(this.getAttribute('data-price'));
        const existingProductIndex = posData.findIndex(item => item.productName === productName);
        if (existingProductIndex !== -1) {
            posData[existingProductIndex].price = productPrice;
            posData[existingProductIndex].quantity++;
        } else {
            const newProduct = {
                productId: productId, // Use retrieved product ID
                productName: productName,
                price: productPrice,
                quantity: 1
            };
            posData.push(newProduct);
        }
        renderPOSTable();
        calculateTotalAmount();
    });
});


