<?php
include("db/cn.php");

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 is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['addamount'])) {
    // Retrieve opening amount from the form
    $openingAmount = $_POST['opening_amount'];
	$userName2 = $_SESSION['user_name'];
	$userRole2 = $_SESSION['user_role'];
     $date_time = date("Y-m-d");
	 $outlet_address1 = $_SESSION['outlet_address'];
	$outlet_name1 = $_SESSION['outlet_name'];

    // Insert the opening amount into the database
    $insertQuery = "INSERT INTO opening_amount (open_cash,login_user,outlet_name,outlet_address,date_time,role) VALUES ('$openingAmount','$userName2','$outlet_name1','$outlet_address1','$date_time','$userRole2')";
    $result = mysqli_query($connection, $insertQuery);

    if ($result) {
        echo "";
    } else {
        echo "Error: " . mysqli_error($connection);
    }
}



?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS Point Of Sale</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/custom_css.css" >    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">

</head>
<style>
 #table-container-wrapper {
    max-height: 500px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
@media (max-width: 880px) {
    .col-4 {
        width: 33.33% !important;
    }
    .fa-wifi {
        display: none !important;
    }
    .col-6 {
        width: 50% !important;
    }
}

@media (min-width: 880px) {
    .sidebar {
        width: 100%;
        /* Change sidebar width to 100% on mobile */
        max-width: 120px; /* Set maximum width for the sidebar */
    }
}

@media (min-width: 880px) {
    .main-content {
        margin-left: ; /* Width of the sidebar */
    }
}

/* Added new class to control overlay */
.overlay {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.6);
    z-index: 999;
    display: none; /* Initially hidden */
}
    /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
        background-color: #060606;
        position: fixed;
        bottom: 0;
        top: 60px;
        transition: transform 0.3s ease-in-out;
        transform: translateX(0);
        z-index: 1;
        height: 100%;
        border-radius: 0px;
		   transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
    }

    .sidebar.hide {
        transform: translateX(-100px);
        /* Move sidebar out of the viewport when it is hidden */
    }

    .sidebar .nav-item {
        padding: 10px 0;
        text-align: center;
        position: relative;
        font-size: 12px;
    }

    .sidebar .nav-link {
        color: #fff;
        position: relative;
        /* Ensure icon and text are positioned relative to the nav link */
        z-index: 2;
        /* Ensure the text and icon are above the hover background */
    }

    .sidebar .nav-link i {
        margin-bottom: 5px;
        /* Adjust the margin of the icon */
    }

    /* Custom styles for hover effect */
    .sidebar .nav-item:hover:after {
        background-color: #fff;
        content: '';
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
        /* Ensure the hover background is below the text and icon */
    }

    .sidebar .nav-item:hover .nav-link {
        color: #0A5064;
    }

    /* Custom styles for divider */
    .sidebar .nav-item:after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 1px;
        background-color: #fff;
        transition: height 0.3s ease-in-out;
        /* Transition effect for smooth animation */
    }

    /* Custom styles for header */
    .header {
        background-color: #060606;
        color: #fff;
        padding: 10px;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 2;
        height: 69px;
        box-shadow: #FFF 2px 0px 0px 0px;
        /* Ensure header appears above sidebar */
    }

    .header .navbar-toggler {
        color: #fff;
    }

    .header .navbar-toggler-icon {
        color: #fff;
        /* Set the color of the toggle button to white */
    }

    .header .navbar-toggler.white {
        color: #fff !important;
        /* Ensure the toggle button is white */
    }

    .header .navbar-brand {
        color: #fff;
        /* Set navbar brand text color to white */
    }

    .header .nav-item .nav-link {
        color: #fff;
        /* Set nav link text color to white */
    }

.main-content {
    margin-top: 50px; /* Height of fixed header */
    margin-left: 100px; /* Initially, set margin-left to 0 */
    padding-top: 30px; /* Height of fixed header */
    transition: margin-left 0.3s ease-in-out; /* Add transition for smoother animation */
}


    /* Custom styles for search bar */
    .search-container {
        display: flex;
        align-items: center;
       width:100%;
        margin: 2px auto;
        float:left;
	}

/* Updated hide class to apply to the overlay */
.sidebar.hide, .overlay.hide {
    transform: translateX(-100%);
}

    .search-input {
        width: 100%;
        padding: 10px 30px 10px 10px;
        /* Adjust padding to accommodate the icon */
        border: 1px solid #ccc;
        border-radius: 20px;
        font-size: 16px;
    }

    .search-icon {
        position: relative;
        left: -25px;
        /* Adjust the position of the icon */
        color: #aaa;
    }

    .search-icon i {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }

    .btn-dark {
        background: #0A5064;
        color: #fff;
        border: 1px solid #0A5064;
    }

    .btn-dark:hover {
        background: #fff;
        color: #0A5064;
        border: 1px solid #0A5064;
    }

    .bg-dark2 {
        background: #8A1218;
        color: #fff;
    }

    .modal-content {
        animation: modal-animation 0.5s;
    }

    @keyframes modal-animation {
        from {
            opacity: 0;
            transform: scale(0.8);
        }

        to {
            opacity: 1;
            transform: scale(1);
        }
    }
			
		/* Style for the opening amount popup */
        .opening-amount-popup {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black */
            z-index: 9999; /* Ensure the popup is on top of other content */
        }

    .opening-amount-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #0A5064;
    padding: 6px;
    border-radius: 10px;
    width: 400px;
}

		        #searchResults {
            position: absolute;
            background-color: #ffff;
            border: 1px solid #ddd;
            max-height: 300px;
            overflow-y: auto;
            width: 66%;
            display: none;
			text-align:left;
        }
        #searchResults div {
            padding: 10px;
            cursor: pointer;
        }
        #searchResults div:hover {
            background-color: #f1f1f1;
        }
		
	
</style>


<!-- Sidebar -->
<?php include("common/hd.php"); ?>
<?php include("common/sd.php"); ?>
<div class="main-content">
<?php
// Check if the user is logged in
if(isset($_SESSION['user_name']) && isset($_SESSION['user_role'])) {
    // Check if the opening amount has been submitted in this session
    if (!isset($_SESSION['opening_amount_submitted'])) {
        // Output JavaScript to show the opening amount popup on page load
        echo '<script>
                // Function to hide the opening amount popup
                function hideOpeningAmountPopup() {
                    var openingAmountPopup = document.getElementById("openingAmountPopup");
                    openingAmountPopup.style.display = "none";
                }

                // JavaScript code to show the opening amount popup on page load
                document.addEventListener("DOMContentLoaded", function() {
                    var openingAmountPopup = document.getElementById("openingAmountPopup");
                    // Check if the opening amount popup should be displayed
                    if (!localStorage.getItem("openingAmountEntered")) {
                        openingAmountPopup.style.display = "block"; // Show the popup
                    }
                });

                // JavaScript code to handle form submission
                document.getElementById("openingAmountForm").addEventListener("submit", function(event) {
                    // Prevent the default form submission behavior
                    event.preventDefault();
                    
                    // Retrieve opening amount from the form
                    var openingAmount = document.getElementById("opening_amount").value;
                    
                    // Send the opening amount data to the server using AJAX
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "'.$_SERVER["PHP_SELF"].'", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === XMLHttpRequest.DONE) {
                            if (xhr.status === 200) {
                                console.log("Response from server:", xhr.responseText); // Log the response from the server
                                // If the request is successful, hide the opening amount popup
                                hideOpeningAmountPopup();
                                // Set a flag in local storage indicating that the opening amount has been entered
                                localStorage.setItem("openingAmountEntered", "true");
                                // Set a session variable to indicate that the opening amount has been submitted
                                ' . $_SESSION['opening_amount_submitted'] = true . '
                            } else {
                                // If there is an error, log it to the console
                                console.error("Error:", xhr.statusText);
                            }
                        }
                    };
                    xhr.send("opening_amount=" + encodeURIComponent(openingAmount));
                });
              </script>';
    }
}
?>
<div id="openingAmountPopup" class="opening-amount-popup">
    <div class="opening-amount-content">
        <div class="card">
            <div class="card-header">Enter Opening Amount</div>
            <div class="card-body">
                <form id="openingAmountForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                    <div class="mb-3">
                        <label for="opening_amount" class="form-label">Opening Amount</label>
                        <input type="text" class="form-control" id="opening_amount" name="opening_amount" required>
                    </div>
                    <button type="submit" class="btn btn-dark from-control" name="addamount">Add Open-Amount</button>
                    <button onclick="refreshPage()" class="btn btn-dark">Later</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <div class="row">
        <div class="col-sm-5" style="border:1px solid #CCCCCC; padding:7px; border-radius:4px;">
            <center>
                <div id="category-buttons">
                 	<?php
        
        
        if ($connection->connect_error) {
            die("Connection failed: " . $connection->connect_error);
        }
        
        $sql12 = "SELECT DISTINCT name FROM products";
        $result12 = $connection->query($sql12);
        
        $categories = [];
        if ($result12->num_rows > 0) {
            while ($row12 = $result12->fetch_assoc()) {
                $categories[] = $row12['name'];
            }
        }
        ?>
     <input type="text" id="search-input" autocomplete="off" class="form-control" placeholder="Search Product By Name:-">
     <div id="searchResults"></div>
                </div>
            </center>
        </div>
        
        <div class="col-sm-3"></div>
        
            <div class="col-sm-2" style=" padding:7px; border-radius:4px;" >
        


      
         
            
           

     <center>       
<!-- Button to trigger modal -->
<a href="update_qty.php"><button type="button" class="btn btn-dark   " >
              Qty <i class="fas fa-balance-scale"></i>
            </button>  </a>

<!-- Modal -->

 <a href="update_price.php"><button type="button" class="btn btn-dark   " >
             Price <i class="fas fa-dollar-sign"></i>  
            </button></a>
</center>
            </div>
        <div class="col-sm-2" style=" padding:7px; border-radius:4px;" >
        


      
         
            
           

     <center>       
<!-- Button to trigger modal -->
<button type="button" class="btn btn-dark" data-toggle="modal" data-target="#exampleModal">
  Add <i class="fas fa-box-open"></i>
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" style="margin-top:100px;">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add Product Manually</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="input-group mb-3">
            <input type="text" class="form-control" placeholder="Product Name" id="manual-product-name">
            <input type="number" class="form-control" placeholder="Product Price" id="manual-product-price">
            <div class="input-group-append">
                <button class="btn btn-dark" type="button" id="add-manual-product" onclick="popProduct()">+</button>
            </div>
        </div>
      </div>
    </div>
  </div>
</div>
<button onclick="refreshPage()" class="btn btn-dark"> Reset&nbsp;<i class="fa fa-recycle"></i></button>
</center>
            </div>
        </div>
    </div>
<br>
<div class="container">
    <div class="row">
    
        <div class="col-sm-7" id="product-container-wrapper">
        
            <div class="row" id="products-container">
    <!--<input type="text" id="" placeholder="Search products">-->
   <?php
// Fetch products from database
$query = "SELECT * FROM products ";
$result = mysqli_query($connection, $query);

if ($result) {
    echo '<table id="productTable1" class="table table-stripped table-sm text-center " style="font-size:12px; border-radius:7px;">
            <thead>
                <tr style="color:#fff; background:#212529;">
                    <th>Qty</th>
                    <th>Name</th>
					
                    <th>Retail Per Pack</th>
                    <th>Retail Per Unit</th>
                </tr>
            </thead>
            <tbody>';

    $index = 0; // Initialize $index here
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr class="product-row add-product table-hover" data-category="'.$row['category'].'" data-companyCategory="'.$row['category'].'" data-name="'.$row['name'].'" data-product-id="'.$row['id'].'" data-price="'.$row['unit_pr'].'" data-supplier="'.$row['supplier_name'].'" data-company="'.$row['company_category'].'" data-index="'.$index.'" tabindex="0">
                <td class="bg-dark text-white text-center" style="font-size:13px;width:40px;border-radius:10px;">'.$row['total_quantity'].'</td>
                <td class="text-capitalize " style="font-weight:600;">'.$row['name'].'</td>
                
				<td style="font-weight:600;">Rs '.$row['price'].' /-</td>
				
                <td style="font-weight:600;">Rs '.$row['unit_pr'].' /-</td>
              </tr>';
        $index++; // Increment $index for each row
    }

    echo '</tbody></table>';
}
?>
</div> 
        </div>
        <div class="col-sm-5">
        

                <div class="row">
          <div id="table-container-wrapper">      
    <table class="table table-striped text-center table-sm " style=" height:448px;; border:1px solid #F2E6E6; box-shadow:0px 0px 0px 1px #ccc; border-radius:8px;">
    <thead>
        <tr class="text-white text-center" style="font-size:5px;">
            <!-- Add your table headers here -->
        </tr>
    </thead>
    <tbody id="pos-table-body" class="text-center text-capitalize">
        <!-- This tbody will have a maximum height of 400px and en able scrolling when content exceeds the height -->
    </tbody>
</table>
          </div>
            <br>
            <!-- Discount input -->
            
            
            <!-- Coupon input (similar to discount) -->
            <!-- Tax display (if required) -->
           <div class="col-sm-3 col-4">
               <button type="button" class="btn btn-dark btn-sm form-control" data-bs-toggle="modal" data-bs-target="#exampleModal2">
                   Customer &nbsp; <i class="fa fa-male"></i>
                   </button>
                
                <!-- Modal -->
                <div class="modal fade" id="exampleModal2" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalLabel">Enter Customer Information</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <!-- Form inputs -->
                                <input class="form-control mb-3" type="text" id="customer-input" name="customer" placeholder="Customer Name" />
                                <input class="form-control mb-3" type="text" name="phone" id="phone-input" placeholder="Customer Phone">
                                <input class="form-control mb-3" type="hidden" name="" id="sale-by-input" placeholder="">
                                
                            </div>
                        </div>
                    </div>
                </div>
           </div>
           
           
           
           
           
           <div class="col-sm-3 col-4">
           <div class="input-group mb-3">
           <button type="button" class="btn btn-dark btn-sm form-control" data-bs-toggle="modal" data-bs-target="#exampleModal3">
                   Discount &nbsp; <i class="fa fa-percentage"></i>
                   </button>
                
                <!-- Modal -->
                <div class="modal fade" id="exampleModal3" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalLabel">Discount Amount</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <!-- Form inputs -->
                               <input type="text" class="form-control" placeholder="Apply Discount" id="discount-input">
                                <div class="input-group-append">
                                    <button class="btn btn-dark" type="button" onclick="applyDiscount()"><i class="fa fa-percentage "></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
               
            </div>
           </div>
           
<div class="col-sm-5 col-4">
    <select class="form-control mb-3" name="paid_by" id="paid-by-input" required>
        
        <option value="cash">Cash</option>
        <option value="card">Card</option>
        <option value="other">Other</option>
        <option value="credit">Credit</option>
    </select>
</div>
           
           <div class="col-sm-12">
          <div id="total-amount" class="text-center"
           style="width:450px;padding:6px; border-radius:8px; margin-top:">
            <h5 style="font-size:12px;">Sub Total: Rs </h5>
            <h6  style="font-size:12px;" id="tax-info">Tax (0%): Rs </h6>
            <h6  style="font-size:12px;" id="discount-info">Discount: Rs </h6>
            <h6  style="font-size:12px;" id="total-amount-info">Total Amount : Rs </h6>
          </div>
           </div>
           <br><br>
       <div class="col-sm-12"></div>
            <div class="col-sm-6 col-6"><button class="btn btn-dark form-control" id="submit-pos">Pay Now</button></div>
            
            <!-- Remaining content -->
            <div class="col-sm-6 col-6"><button id="holdTransactionBtn" class="btn btn-dark form-control">Hold Bill</button></div>
       
           </div>
        </div>
    </div>
</div>

</div>
<script src="../js/custom.js"></script>

 <!-- JavaScript code -->
   <script>
document.addEventListener("DOMContentLoaded", function () {
    var sidebar = document.getElementById("sidebar");
    var overlay = document.createElement("div");
    overlay.classList.add("overlay");
    document.body.appendChild(overlay);

    function toggleSidebar() {
        sidebar.classList.toggle("hide");
        overlay.classList.toggle("hide");

        var mainContent = document.querySelector(".main-content");
        if (sidebar.classList.contains("hide")) {
            mainContent.style.marginLeft = "0";
        } else {
            mainContent.style.marginLeft = "100px"; // Width of the sidebar
        }
    }

    overlay.addEventListener("click", function () {
        toggleSidebar();
    });

    // Add toggle functionality to navbar toggler
    var navbarToggler = document.querySelector(".navbar-toggler");
    navbarToggler.addEventListener("click", function () {
        toggleSidebar();
    });

    // Automatically hide sidebar on all screen sizes
    // sidebar.classList.add("hide");
    // overlay.classList.add("hide");
    
    // Add class to body to prevent scrolling when sidebar is open
    // document.body.classList.add("noscroll");

    // Check if screen size is larger than a certain threshold (e.g., 768px for desktop screens)
    function checkScreenSize() {
        if (window.innerWidth > 768) {
            sidebar.classList.remove("hide");
            overlay.classList.remove("hide");
        } else {
            sidebar.classList.add("hide");
            overlay.classList.add("hide");
        }
    }

    // Check screen size on initial load and whenever the window is resized
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
});
 
   
document.addEventListener("DOMContentLoaded", function() {
    var tableRows = document.querySelectorAll(".product-row");
    var currentIndex = -1;

    document.addEventListener("keydown", function(event) {
        if (event.key === "ArrowDown") {
            currentIndex = Math.min(currentIndex + 1, tableRows.length - 1);
            updateSelection();
        } else if (event.key === "ArrowUp") {
            currentIndex = Math.max(currentIndex - 1, 0);
            updateSelection();
        } else if (event.key === "Tab") {
            if (!event.shiftKey && currentIndex !== -1) {
                currentIndex = -1; // Reset currentIndex
                updateSelection();
                return; // Allow default tab behavior
            }
        } else if (event.key === "Enter") {
            if (currentIndex !== -1) {
                // Simulate click event on the selected row
                var selectedProduct = tableRows[currentIndex];
                selectedProduct.click();
                event.preventDefault(); // Prevent form submission or other default behavior
            }
        } else if (event.key === "ArrowLeft") {
            if (currentIndex !== -1) {
                var selectedProduct = tableRows[currentIndex];
                selectedProduct.focus();
            }
        } else if (event.key === "ArrowRight") {
            if (currentIndex === tableRows.length - 1) {
                var postabelbody = document.getElementById("POSTABELBODY");
                if (postabelbody) {
                    postabelbody.focus();
                    currentIndex = -1;
                }
            }
        }
    });

    function updateSelection() {
        tableRows.forEach(function(row, index) {
            if (index === currentIndex) {
                row.classList.add("selected");
                row.focus(); // Set focus on the selected row
            } else {
                row.classList.remove("selected");
            }
        });
    }

    tableRows.forEach(function(row, index) {
        row.addEventListener("focus", function() {
            currentIndex = index; // Update the current index when row is focused
        });
    });
});






  document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("search-input").addEventListener("input", function() {
        var searchText = this.value.toLowerCase();
        var rows = document.querySelectorAll(".product-row");

        rows.forEach(function(row) {
            var productName = row.querySelector("td:nth-child(2)").textContent.toLowerCase();
            if (productName.includes(searchText)) {
                row.style.display = "table-row";
            } else {
                row.style.display = "none";
            }
        });
    });
});


document.addEventListener("DOMContentLoaded", function () {
    const categories = <?php echo json_encode($categories); ?>;
    const searchInput = document.getElementById('searchInput');
    const searchResults = document.getElementById('searchResults');
    const products = document.querySelectorAll('.product-row');

    searchInput.addEventListener('input', function () {
        const query = this.value.trim().toLowerCase();
        if (query === '') {
            searchResults.style.display = 'none';
            showAllProducts();
            return;
        }
        const filteredCategories = categories.filter(category => category.toLowerCase().includes(query));
        renderResults(filteredCategories);
        filterProducts(filteredCategories);
    });

    searchInput.addEventListener('blur', function () {
        setTimeout(() => {
            searchResults.style.display = 'none';
        }, 200); // Delay hiding dropdown to allow click event on dropdown items
    });

    function renderResults(results) {
        let html = '';
        results.forEach(result => {
            html += `<div>${result}</div>`;
        });
        searchResults.innerHTML = html;
        searchResults.style.display = 'block';
    }

    function filterProducts(filteredCategories) {
        products.forEach(function (product) {
            const category = product.getAttribute('data-category');
            if (!filteredCategories.includes(category)) {
                product.style.display = 'none';
            } else {
                product.style.display = 'table-row';
            }
        });
    }

    function showAllProducts() {
        products.forEach(function (product) {
            product.style.display = 'table-row';
        });
    }

    searchResults.addEventListener('click', function (event) {
        const clickedItem = event.target;
        if (clickedItem.tagName === 'DIV') {
            searchInput.value = clickedItem.innerText;
            searchResults.style.display = 'none';
            filterProducts([clickedItem.innerText]);
        }
    });
});

 
    // Add an event listener to the button
    document.getElementById('holdTransactionBtn').addEventListener('click', function() {
        holdTransaction(); // Call the holdTransaction function when the button is clicked
    });

    // Function to submit POS data for holding transaction
    function holdTransaction() {
        console.log("Hold transaction function called"); // Log a message to the console to check if the function is called

        // Create a form element
        const form = document.createElement('form');
        form.setAttribute('method', 'post');
        form.setAttribute('action', 'hold_pay.php'); // Replace 'hold_pay.php' with the actual PHP file to handle the form submission

        // Retrieve items data from posData array
        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; // Assuming totalAmountDiv is defined elsewhere
        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); // Assuming discountAmount is defined elsewhere
        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();
    }
</script>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://rawgit.com/cozmo/jsQR/master/dist/jsQR.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>


</body>
</html>