<?php include("../db/cn.php"); $products_query = "SELECT * FROM products"; $products_result = mysqli_query($connection, $products_query); // Check if order ID is provided if (!isset($_GET["order_id"])) { exit("Order ID is missing."); } $order_id = mysqli_real_escape_string($connection, $_GET["order_id"]); $products_query2 = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$order_id'"); // Store fetched products from the first table in an array $products = array(); while ($row = mysqli_fetch_array($products_result)) { $product = array( "name" => $row["name"], "product_id" => $row["product_id"], "unit_price" => $row["unit_pr"], "trade_price" => $row["trade_price"], "retail_price" => $row["price"], "supplier_name" => $row["supplier_name"], "category" => $row["company_category"], "company_category" => $row["category"], "total_quantity" => $row["total_quantity"] ); $products[] = $product; } // Check if session variables are set if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) { $userName = $_SESSION['user_name']; $userRole = $_SESSION['user_role']; $outlet_address = $_SESSION['outlet_address']; $outlet_name = $_SESSION['outlet_name']; } // Check if the form was submitted if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) { // Initialize variables from form fields or set default values $orderId = $order_id; $dateTime = $_POST['date_time'] ?? ''; // Handle undefined array keys safely $taxAmount = $_POST['tax_amount'] ?? 0; $totalAmount = $_POST['total_input'] ?? 0; $paidBy = $_POST['paid_by'] ?? ''; $customerName = $_POST['customer_name'] ?? ''; $customerPhone = $_POST['customer_phone'] ?? ''; $discountedAmount = $_POST['discounted'] ?? ''; $discounted = $_POST['discount_amount'] ?? ''; $discountper = $_POST['discount_percentage'] ?? ''; $cashAmount = $_POST['cash_amount'] ?? ''; $changeAmount = $_POST['change_amount'] ?? ''; // Initialize arrays from form fields or set default values $productIds = $_POST['productIds'] ?? []; $productNames = $_POST['productNames'] ?? []; $productPrices = $_POST['productPrices'] ?? []; $productQuantities = $_POST['productQuantities'] ?? []; $retailPrices = $_POST['retailPrices'] ?? []; $supplierNames = $_POST['supplierNames'] ?? []; $companyCategories = $_POST['companyCategories'] ?? []; $companies = $_POST['companies'] ?? []; // Loop through product details from the first table and insert into database foreach ($productIds as $key => $productId) { // Retrieve corresponding product details $productName = $productNames[$key] ?? ''; $productPrice = $productPrices[$key] ?? ''; $productQuantity = $productQuantities[$key] ?? ''; $productTotal = $retailPrices[$key] ?? ''; $supplierName = $supplierNames[$key] ?? ''; $companyCategory = $companyCategories[$key] ?? ''; $company = $companies[$key] ?? ''; // Insert product sale into database mysqli_query($connection, "INSERT INTO m_order (product_id, supplier_name, company, company_category, product_name, product_price, product_quantity, product_total, tax_amount, total_amount, paid_by, customer_name, customer_phone, discount_amount, discounted, discount_per, cash_amount, change_amount, order_id, outlet_name, login_user, user_role, outlet_address, date_time) VALUES ('$productId', '$supplierName', '$company', '$companyCategory', '$productName', '$productPrice', '$productQuantity', '$productTotal', '$taxAmount', '$totalAmount', '$paidBy', '$customerName', '$customerPhone', '$discountedAmount', '$discounted', '$discountper', '$cashAmount', '$changeAmount', '$orderId', '$outlet_name', '$userName', '$userRole', '$outlet_address', '$dateTime')"); // Update product quantity in the products table mysqli_query($connection, "UPDATE products SET total_quantity = total_quantity - $productQuantity WHERE product_id = '$productId'"); // Check if the product quantity is less than zero (returned products) if ($productQuantity < 0) { // Increase the quantity in the products table mysqli_query($connection, "UPDATE products SET total_quantity = total_quantity - ($productQuantity * -1) WHERE product_id = '$productId'"); } } // Handling existing products in the order (First Table) $existingProductIds = $_POST['existingProductIds'] ?? []; $existingProductNames = $_POST['existingProductNames'] ?? []; $existingProductPrices = $_POST['existingProductPrices'] ?? []; $existingProductQuantities = $_POST['existingProductQuantities'] ?? []; $existingRetailPrices = $_POST['existingRetailPrices'] ?? []; $existingSupplierNames = $_POST['existingSupplierNames'] ?? []; $existingCompanyCategories = $_POST['existingCompanyCategories'] ?? []; $existingCompanies = $_POST['existingCompanies'] ?? []; foreach ($existingProductIds as $key => $productId) { $productName = $existingProductNames[$key] ?? ''; $productPrice = $existingProductPrices[$key] ?? ''; $productQuantity = $existingProductQuantities[$key] ?? ''; $productTotal = $existingRetailPrices[$key] ?? ''; $supplierName = $existingSupplierNames[$key] ?? ''; $companyCategory = $existingCompanyCategories[$key] ?? ''; $company = $existingCompanies[$key] ?? ''; $pr_total = $productQuantity * $productPrice; mysqli_query($connection, "INSERT INTO m_order (product_id, supplier_name, company, company_category, product_name, product_price, product_quantity, product_total, tax_amount, total_amount, paid_by, customer_name, customer_phone, discount_amount, discounted, discount_per, cash_amount, change_amount, order_id, outlet_name, login_user, user_role, outlet_address, date_time) VALUES ('$productId', '$supplierName', '$company', '$companyCategory', '$productName', '$productPrice', '$productQuantity', '$pr_total', '$taxAmount', '$totalAmount', '$paidBy', '$customerName', '$customerPhone', '$discountedAmount', '$discounted', '$discountper', '$cashAmount', '$changeAmount', '$order_id', '$outlet_name', '$userName', '$userRole', '$outlet_address', '$dateTime')"); // Update product quantity in the products table if ($productQuantity > 0) { // Decrease the quantity in the products table mysqli_query($connection, "UPDATE products SET total_quantity = total_quantity - $productQuantity WHERE product_id = '$productId'"); } elseif ($productQuantity < 0) { // Increase the quantity in the products table mysqli_query($connection, "UPDATE products SET total_quantity = total_quantity - ($productQuantity * -1) WHERE product_id = '$productId'"); } } // Delete query // mysqli_query($connection, "DELETE FROM log_user_sales WHERE order_id = '$orderId'"); // Redirect to print page header("Location: order_m.php?order_id=$orderId"); exit(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ghani Glass House</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <style> html, body { height: 100%; margin: 0; padding: 0; font-family: Arial, sans-serif; background-image:url(img/glass-sheet.jpg); background-size: cover; background-position: center; background-attachment: fixed; } .wrapper { display: flex; flex-direction: column; height: 100%; } .header, .footer { width: 100%; height: 70px; background-color: #060606; color: #fff; text-align: ; /* Center text vertically */ } .content { flex: 1; overflow-y: auto; padding: 10px; } #product-container-wrapper { max-height: 220px; overflow-y: auto; } .dropdown-options { display: none; position: absolute; z-index: 1000; width: calc(89% - 2px); max-height: 200px; overflow-y: auto; border: 1px solid #ccc; background-color: #fff; } .option { padding: 5px 10px; cursor: pointer; transition: background-color 0.3s; } .option:hover, .option.highlight { background-color: #353535; color: #fff; } @keyframes blink { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } } #total-amount { font-size: 46px; font-weight: 700; color: #0A5064; animation: blink 1s step-start infinite; } label { font-weight: 600; } .in_c { border: 1.5px solid #0A5064; } img.pulse { width: 60px; height: 60px; animation: pulse 2s infinite; } @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.2); } 100% { transform: scale(1); } } .btn-success{ background:#0A5064; color:#fff; border:1px solid #353535; } </style> </head> <body> <div class="wrapper"> <div class="header row"> <div class="col-sm-3"> <a href="addproduct.php"><img class="pulse" src="img/print_logo.png" width="60" height="60"></a> </div> <div class="col-sm-6"> <h3 style="color:#fff; text-align:center;line-height:70px; font-weight:600;">GHANI GLASS</h3> </div> <div class="col-sm-3"></div> </div> <div class="content"> <div class="container"> <form action="order_m.php?order_id=<?php echo $order_id; ?>" method="post" enctype="multipart/form-data"> <div class="container"> <div class="row" style=" border:1px solid #0A5064; border-radius:7px; background:#FFF;padding:10px;"> <div class="col-sm-5"> <br> <div class="form-group" style=" border:1px solid #ccc; border-radius:7px; background:#EFEFE5;padding:10px;"> <input type="text" id="searchInput" class="search-input form-control in_c" placeholder="Enter The Product" /> <div id="filteredOptions" class="dropdown-options"></div> </div> </div> <div class="col-sm-4"></div> <div class="col-sm-3" style="background:#353535; text-align:center; padding:15px;border-radius:10px;border:1px solid #0A5064; "> <span style="font-size:46px; font-weight:700; color:#fff; " id="total-amount">0.00</span> </div> </div> <br> <div class="row"> <div class="col-sm-12" id="product-container-wrapper" style="height:auto; border:1px solid #0A5064; border-radius:7px; background:#F5F5F5;padding:10px;"> <table class="table table-striped table-sm text-center"> <thead> <tr class="bg-dark text-white"> <th>T.Qty</th> <th>Item Code</th> <th>Description</th> <th>Modify.Qty</th> <th>Unit Price</th> <!--<th>Retail Price Per</th>--> <th>Amount</th> </tr> </thead> <tbody> <?php while($row = mysqli_fetch_array($products_query2)) { ?> <tr> <td style="color:#0A5064; font-weight:700;"><?php echo $row["product_quantity"]; ?></td> <td style="color:#0A5064; font-weight:700;"><?php echo $row["product_id"]; ?></td> <td style="color:#353535; font-weight:700;"><?php echo $row["product_name"]; ?></td> <td> <center> <input type="number" name="existingProductQuantities[]" class="form-control qty-input-second-table" style="width:100px; border:1px solid #0A5064;" /> </center> </td> <td style="color:#0A5064; font-weight:600;"><?php echo $row["product_price"]; ?></td> <td style="color:#353535; font-weight:600;" class="total-price-second-table"></td> <input type="hidden" name="existingProductIds[]" value="<?php echo $row["product_id"]; ?>"> <input type="hidden" name="existingProductNames[]" value="<?php echo $row["product_name"]; ?>"> <input type="hidden" name="existingProductPrices[]" value="<?php echo $row["product_price"]; ?>"> <input type="hidden" class="total-price-second-table" name="existingRetailPrices[]" value="<?php echo $row["product_total"]; ?>"> <input type="hidden" name="existingSupplierNames[]" value="<?php echo $row["supplier_name"]; ?>"> <input type="hidden" name="existingCompanyCategories[]" value="<?php echo $row["company_category"]; ?>"> <input type="hidden" name="existingCompanies[]" value="<?php echo $row["company"]; ?>"> </tr> <?php } ?> </tbody> </table> </div> <div class="col-sm-12" id="product-container-wrapper" style="height:auto; border:1px solid #0A5064; border-radius:7px; background:#F5F5F5;padding:10px;margin-top:20px;"> <table id="cart-table" class="table table-striped table-sm text-center"> <thead> <tr class="" style="color:#F5F5F5;" > <th>R.Qty</th> <th>Item Code</th> <th>Description</th> <th>Qty</th> <th>Unit Price</th> <th>Amount</th> </tr> </thead> <tbody> <!-- Cart items will be dynamically added here --> </tbody> </table> <!-- Hidden inputs for additional required fields --> <input type="hidden" name="outlet_name" value="<?php echo $outlet_name; ?>" /> <input type="hidden" name="login_user" value="<?php echo $userName; ?>" /> <input type="hidden" name="user_role" value="<?php echo $userRole; ?>" /> <input type="hidden" name="outlet_address" value="<?php echo $outlet_address; ?>" /> <input type="hidden" name="date_time" value="<?php echo date('Y-m-d'); ?>" /> <div id="hidden-fields-container"></div> </div> </div> <div class="row" style="margin-top:30px;"> <div class="col-sm-12" style="background:#F5F5F5; padding:18px; border:1px solid #0A5064; border-radius:7px;"> <div class="row"> <div class="col-sm-2"> <div class="form-group"> <label>Total</label> <input type="number" id="total-input" name="total_input" class="form-control in_c" readonly /> </div> </div> <div class="col-sm-2"> <div class="form-group"> <label>Bill Amount</label> <input type="number" id="discount-input" name="discounted" class="form-control in_c" oninput="calculateResult()" /> </div> </div> <div class="col-sm-2"> <div class="form-group"> <label>Discount Amount</label> <input type="number" id="result-input" name="result" class="form-control in_c" readonly /> </div> </div> <div class="col-sm-2"> <div class="form-group"> <label>Discount %</label> <input type="number" id="percentage-display" name="discount_percentage" class="form-control in_c" readonly /> </div> </div> <div class="col-sm-2"> <div class="form-group"> <label>Cash Received</label> <input type="number" id="cash-input" name="cash_amount" class="form-control in_c" /> </div> </div> <div class="col-sm-2"> <div class="form-group"> <label>Cash Return</label> <input type="number" id="balance-input" name="change_amount" class="form-control in_c" readonly /> </div> </div> </div> <br> <div class="row"> <div class="col-sm-2"> <div class="form-group"> <label>S.Tax(0%)</label> <input type="text" class="form-control in_c" name="tax_amount" /> </div> </div> <div class="col-sm-2"> <div class="form-group"> <label>Customer Name</label> <input type="text" class="form-control in_c" name="customer_name" /> </div> </div> <div class="col-sm-2"> <div class="form-group"> <label>Phone</label> <input type="text" class="form-control in_c" name="customer_phone" /> </div> </div> <div class="col-sm-2"> <div class="form-group"> <label>Method</label> <select name="paid_by" class="form-control"> <option value="cash">Cash</option> <option value="credit">Credit</option> <option value="other">Other</option> </select> </div> </div> <div class="col-sm-3"> <br> <button id="bill-button" class="btn btn-success form-control" type="submit" name="submit">Bill</button> <!--<button id="hold-bill-button" class="btn btn-dark" type="submit" name="hold_order">Hold</button>--> </div> </div> </div> </div> <br> <div class="row"> <div class="col-sm-5"></div> <div class="col-sm-2"></div> <div class="col-sm-5"> </div> </div> <div class="row"> <div class="col-sm-12 text-left"> </div> </div> </div> </form> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function () { var products = <?php echo json_encode($products); ?>; var $searchInput = $('#searchInput'); var $filteredOptions = $('#filteredOptions'); var $cartTableBody = $('#cart-table tbody'); var totalAmount = 0; $searchInput.on('input', function () { var value = $(this).val().toLowerCase(); var html = ''; products.forEach(function (product) { if (product.name.toLowerCase().includes(value)) { html += '<div class="option" data-value="' + product.name + '">' + product.name + '</div>'; } }); $filteredOptions.html(html); if (value.length > 0) { $filteredOptions.show(); $filteredOptions.find('.option').first().addClass('highlight'); } else { $filteredOptions.hide(); } }); $searchInput.on('keydown', function (e) { var $options = $('.option'); var currentIndex = $options.index($('.option.highlight')); switch (e.which) { case 40: // Down Arrow e.preventDefault(); if (currentIndex === -1 || currentIndex === $options.length - 1) { $options.first().addClass('highlight').siblings().removeClass('highlight'); } else { $options.eq(currentIndex + 1).addClass('highlight').siblings().removeClass('highlight'); } break; case 38: // Up Arrow e.preventDefault(); if (currentIndex === -1 || currentIndex === 0) { $options.last().addClass('highlight').siblings().removeClass('highlight'); } else { $options.eq(currentIndex - 1).addClass('highlight').siblings().removeClass('highlight'); } break; case 13: // Enter if (currentIndex !== -1) { var selectedProduct = $options.eq(currentIndex).data('value'); addProductToCart(selectedProduct); $searchInput.val(''); $filteredOptions.hide(); return false; // Prevent form submission } break; } }); $(document).on('click', '.option', function (e) { e.stopPropagation(); // Prevent event from propagating to parent elements var selectedProduct = $(this).data('value'); addProductToCart(selectedProduct); $searchInput.val(''); $filteredOptions.hide(); }); function addProductToCart(productName) { var product = products.find(function (p) { return p.name === productName; }); if (product) { var unitPrice = parseFloat(product.unit_price); var productId = product.product_id; var supplierName = product.supplier_name; var companyCategory = product.category; var company = product.company_category; var retailPrice = parseFloat(product.retail_price); var total_quantity = product.total_quantity; var $existingRow = $cartTableBody.find('tr[data-product="' + product.name + '"]'); if ($existingRow.length > 0) { var $qtyInput = $existingRow.find('.qty-input'); var newQty = parseInt($qtyInput.val()) + 1; $qtyInput.val(newQty); var newTotal = unitPrice * newQty; var newRetailPrice = unitPrice * newQty; $existingRow.find('.total-price').text(newTotal.toFixed(2)); // Update hidden input fields var productIndex = $existingRow.index(); $('input[name="productQuantities[]"]').eq(productIndex).val(newQty); $('input[name="retailPrices[]"]').eq(productIndex).val(newRetailPrice.toFixed(2)); } else { var newTotal = unitPrice; var newRetailPrice = unitPrice; // initially equal to unit price var row = '<tr data-product="' + product.name + '">' + '<td style="color:#709806;font-weight:700;">' + total_quantity + '</td>' + '<td style="color:#709806;font-weight:700;">' + productId + '</td>' + '<td style=" color:#000;font-weight:600;">' + product.name + '</td>' + '<td><center><input type="number" class="qty-input form-control" value="1" min="1" style="width:100px; border:1px solid #0A5064;" /></center></td>' + '<td style="color:#709806;font-weight:600;">' + unitPrice + '</td>' + '<td style="display:none;">' + retailPrice + '</td>' + '<td style="font-weight:600;" class="total-price">' + newTotal.toFixed(2) + '</td>' + '</tr>'; $cartTableBody.append(row); // Update hidden input fields with product data $('<input>').attr({ type: 'hidden', name: 'productIds[]', value: productId }).appendTo('#hidden-fields-container'); $('<input>').attr({ type: 'hidden', name: 'productNames[]', value: product.name }).appendTo('#hidden-fields-container'); $('<input>').attr({ type: 'hidden', name: 'productPrices[]', value: unitPrice }).appendTo('#hidden-fields-container'); $('<input>').attr({ type: 'hidden', name: 'productQuantities[]', value: 1 }).appendTo('#hidden-fields-container'); $('<input>').attr({ type: 'hidden', name: 'retailPrices[]', value: newRetailPrice.toFixed(2) }).appendTo('#hidden-fields-container'); $('<input>').attr({ type: 'hidden', name: 'supplierNames[]', value: supplierName }).appendTo('#hidden-fields-container'); $('<input>').attr({ type: 'hidden', name: 'companyCategories[]', value: companyCategory }).appendTo('#hidden-fields-container'); $('<input>').attr({ type: 'hidden', name: 'companies[]', value: company }).appendTo('#hidden-fields-container'); } totalAmount += unitPrice; // Add only the unit price of the new product $('#total-amount').text(totalAmount.toFixed(2)); // Update the displayed total amount $('#total-input').val(totalAmount.toFixed(2)); // Update the hidden input field calculateDiscountedTotal(); // Recalculate discounted total } } // Add event listener for quantity input change $cartTableBody.on('change', '.qty-input', function () { var $row = $(this).closest('tr'); var newQty = parseInt($(this).val()); var productName = $row.data('product'); var product = products.find(function (p) { return p.name === productName; }); var unitPrice = parseFloat(product.unit_price); var newTotal = unitPrice * newQty; var newRetailPrice = unitPrice * newQty; $row.find('.total-price').text(newTotal.toFixed(2)); // Update hidden input fields var productIndex = $row.index(); $('input[name="productQuantities[]"]').eq(productIndex).val(newQty); $('input[name="retailPrices[]"]').eq(productIndex).val(newRetailPrice.toFixed(2)); // Recalculate total amount totalAmount = 0; $cartTableBody.find('.total-price').each(function () { totalAmount += parseFloat($(this).text()); }); $('#total-amount').text(totalAmount.toFixed(2)); $('#total-input').val(totalAmount.toFixed(2)); calculateDiscountedTotal(); }); $(document).on('input', '.qty-input-second-table', function () { var $row = $(this).closest('tr'); var qty = parseInt($(this).val()); var unitPrice = parseFloat($row.find('td:nth-child(5)').text()); var newTotal = qty * unitPrice; $row.find('.total-price-second-table').text(newTotal.toFixed(2)); updateTotalAmount(); // Update the total amount after modifying the quantity }); function updateTotalAmount() { var totalAmount = 0; // Sum up the amounts from the first table $cartTableBody.find('.total-price').each(function () { totalAmount += parseFloat($(this).text()); }); // Sum up the amounts from the second table $('.total-price-second-table').each(function () { totalAmount += parseFloat($(this).text()); }); $('#total-amount').text(totalAmount.toFixed(2)); // Display the total amount $('#total-input').val(totalAmount.toFixed(2)); // Update the hidden input field // Subtract the total of existing table quantities multiplied by their respective unit prices var existingTotal = 0; $('input[name="existingProductQuantities[]"]').each(function (index) { var quantity = parseInt($(this).val()); var unitPrice = parseFloat($('input[name="existingProductPrices[]"]').eq(index).val()); existingTotal += quantity * unitPrice; }); totalAmount -= existingTotal; $('#total-amount').text(totalAmount.toFixed(2)); // Display the adjusted total amount $('#total-input').val(totalAmount.toFixed(2)); // Update the hidden input field } // End of additional code $('#discount-input').on('input', function () { calculateDiscountedTotal(); calculateDiscountPercentage(); }); function calculateDiscountPercentage() { var totalAmount = parseFloat($('#total-input').val()); var discountedAmount = parseFloat($('#discount-input').val()); if (!isNaN(totalAmount) && !isNaN(discountedAmount) && totalAmount > 0) { var discountPercentage = ((totalAmount - discountedAmount) / totalAmount) * 100; $('#percentage-display').val(discountPercentage.toFixed(2)); } else { $('#percentage-display').val('0.00'); } } function calculateDiscountedTotal() { var discountAmount = parseFloat($('#discount-input').val()); if (!isNaN(discountAmount) && discountAmount > 0) { var discountedTotal = totalAmount - discountAmount; $('#discounted-input').val(discountedTotal.toFixed(2)); $('#total-after-discount').text(discountedTotal.toFixed(2)); } else { $('#discounted-input').val(totalAmount.toFixed(2)); $('#total-after-discount').text(totalAmount.toFixed(2)); } } $('#cash-input').on('input', function () { var cashAmount = parseFloat($(this).val()) || 0; var discountedTotal = parseFloat($('#discounted-input').val()) || 0; if (discountedTotal > 0) { var balance = cashAmount - discountedTotal; } else { var totalAmount = parseFloat($('#total-input').val()) || 0; var balance = cashAmount - totalAmount; } $('#balance-input').val(balance.toFixed(2)); }); // New event listener for Bill Amount field $('#bill-amount').on('input', function () { var totalAmount = parseFloat($('#total-amount').val()) || 0; var billAmount = parseFloat($(this).val()) || 0; var discountAmount = totalAmount - billAmount; $('#discount-amount').val(discountAmount.toFixed(2)); }); }); </script> </body></html>