// 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+)?)\s+Supplier:\s*(\S+)\s+Company:\s*(\S+)/);
    if (match && match.length >= 6) {
        return {
            productName: match[1].trim(),
            price: parseFloat(match[2]),
            supplier: match[4].trim(),
            company: match[5].trim()
        };
    } 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;
        // Set supplier and company properties
        productData.supplier = productData.supplier; 
        productData.company = productData.company;
		productData.companyCategory = productData.companyCategory; 
        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');
        row.innerHTML = `
            <td>${index + 1}</td>
            <td style="font-size:14px;">${item.productName}</td>
            <td style="font-size:13px;"><input type="hidden" value="${item.supplier}" name="supplier" style="display:none;" /></td> <!-- Display supplier name -->
            <td  style="font-size:13px;"> <input type="hidden" ${item.company} name="company" style="display:none;" /></td>
			<td style="font-size:13px;"><input type="hidden" ${item.companyCategory} name="company_category" style="display:none;" /></td>  <!-- Display company name -->
            <td style="font-size:15px;">${item.price}</td>
            <td><input type="number" class="form-control" min="1" value="${item.quantity}" data-index="${index}"></td>
            <td><button class="btn btn-danger btn-remove" style="border-radius:20px; font-size:7px;" data-index="${index}">X</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.00;

            // 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 (0%): Rs ${totalTaxAmount.toFixed(2)}</h6>
                                <h6 style="font-size:12px;" id="discount-info">Discount: Rs ${discountAmount.toFixed(2)} </h6>
                                <h6 style="font-size:12px;" id="total-amount-info">Total Amount : 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.');
                }
            }
        });
		
		
		// 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 productPrice = parseFloat(this.getAttribute('data-price'));
        const supplier = this.getAttribute('data-supplier'); // Get supplier information
        const company = this.getAttribute('data-company'); 
		const companyCategory = this.getAttribute('data-companyCategory'); // Get company information
        const existingProductIndex = posData.findIndex(item => item.productName === productName);
        if (existingProductIndex !== -1) {
            posData[existingProductIndex].price = productPrice;
            posData[existingProductIndex].quantity++;
        } else {
            const newProduct = {
                productName: productName,
                supplier: supplier, // Add supplier name here
                company: company, 
				companyCategory: companyCategory,// Add company name here
                price: productPrice,
                quantity: 1
            };
            posData.push(newProduct);
        }
        renderPOSTable();
        calculateTotalAmount();
    });
});

        // 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);
						
							 // Include supplier, company, and companyCategory data
				const supplierInput = document.createElement('input');
				supplierInput.setAttribute('type', 'hidden');
				supplierInput.setAttribute('name', `supplier[${index}]`);
				supplierInput.value = item.supplier;
				form.appendChild(supplierInput);
		
				const companyInput = document.createElement('input');
				companyInput.setAttribute('type', 'hidden');
				companyInput.setAttribute('name', `company[${index}]`);
				companyInput.value = item.company;
				form.appendChild(companyInput);
		
				const companyCategoryInput = document.createElement('input');
				companyCategoryInput.setAttribute('type', 'hidden');
				companyCategoryInput.setAttribute('name', `company_category[${index}]`);
				companyCategoryInput.value = item.companyCategory;
				form.appendChild(companyCategoryInput);
				
				
			});

            // 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.1).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();
        }