<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ပစ္စည်းပြောင်းရန်</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css">
<script src="https://kit.fontawesome.com/ae360af17e.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="css/style.css">
<link rel="icon" href="image/logo.png" type="image/png">
</head>
<style> 
      video {
        width:100%;
        height: 200px;

    object-fit: cover; /* Ensures the video fills the container */
    display: block;
  }

</style>

<style>
        /* Basic styling for dropdown suggestions */
        #suggestions {
            border: 1px solid #ddd;
            max-height: 150px;
            overflow-y: auto;
            display: none;
            position: absolute;
            margin-left: 130px;
            margin-top:50px;
            background-color: darkslategray;
            
        }

        #suggestions div {
            padding: 8px;
            cursor: pointer;
        }

        #suggestions div:hover {
            background-color: #f0f0f0;
        }
</style>

<script>
        function formatNumber(input) {
            // Remove all non-digit characters
            let value = input.value.replace(/\D/g, '');
            
            // Format the number with commas
            let formattedValue = new Intl.NumberFormat().format(value);
            
            // Update the input value
            input.value = formattedValue;
        }

        document.addEventListener('DOMContentLoaded', function () {
            const formattedInput = document.getElementById('formatted');
            formattedInput.addEventListener('input', function () {
                formatNumber(this);
            });
        });
    </script>


<?php
session_start();
                                
if (isset($_SESSION['browser_id'])) {
    $browserId = $_SESSION['browser_id'];
} else {
    // Generate a new browser ID
    $browserId = generateUniqueBrowserId();

    // Store the browser ID in the session for future use
    $_SESSION['browser_id'] = $browserId;
}


include "database/database.php";
include "database/data.php";
include "cal_pro_remain.php";
include "login_check.php";

if (isset($_POST['add'])) {
    $barcode = $_POST['barcode'];
    $product_name = $_POST['product_name'];
    $amount = $_POST['amount'];
    $change_type = $_POST['change_type'];

    // Check for user in the database
    $sql = "SELECT user_name FROM ".$user_database." WHERE browser_id='$b_id' LIMIT 1";
    $result = mysqli_query($connection, $sql);
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $user = $row['user_name'];
        $date = date('Y-m-d');

        // Check for the product by barcode or product name
        $productSql = ($barcode != '')
            ? "SELECT * FROM ".$product." WHERE (barcode='$barcode' OR barcode_1='$barcode') AND delete_d='0' LIMIT 1"
            : "SELECT * FROM ".$product." WHERE product_name='$product_name' AND delete_d='0' LIMIT 1";
            
        $productResult = mysqli_query($connection, $productSql);
        if ($productResult && mysqli_num_rows($productResult) > 0) {
            $productRow = mysqli_fetch_assoc($productResult);

            // Assign values from the product table if needed
            $barcode = $barcode ?: $productRow['barcode'];
            $product_name = $productRow['product_name'];
            $unit = $productRow['unit'];
            $pieces = $productRow['pieces'];
            $package_exist = $productRow['package_exist'];
            $unit_exist = $productRow['unit_exist'];

            if ($change_type == 'unit' && $package_exist >= $amount) {
                // Update the product_change table for unit change
                $insertSql = "INSERT INTO ".$product_change." (barcode, name, unit, pieces, amount_unit, amount_pieces, user_name, date)
                              VALUES ('$barcode', '$product_name', '$amount', '0', '$unit', '$pieces', '$user', '$date')";
                mysqli_query($connection, $insertSql);
                header('Location: product_change.php');
                exit;
            } elseif ($change_type != 'unit' && $unit_exist >= $amount) {
                // Update the product_change table for pieces change
                $insertSql = "INSERT INTO ".$product_change." (barcode, name, unit, pieces, amount_unit, amount_pieces, user_name, date)
                              VALUES ('$barcode', '$product_name', '0', '$amount', '$unit', '$pieces', '$user', '$date')";
                mysqli_query($connection, $insertSql);
                header('Location: product_change.php');
                exit;
            } else {
                echo "<script>alert('".$product_name." လက်ကျန်မလုံလောက်ပါ'); window.location.href = 'product_change.php';</script>";
            }
        }
    }
}



if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["id"])) {
    $id = $connection->real_escape_string($_POST["id"]);
    echo "Received id: " . $id;

        $query = "DELETE FROM ".$product_change." WHERE id = '$id'";
        if ($connection->query($query)) {
            echo 'Deleted successfully.';
        } else {
            echo 'alert("Update failed!");';
        }
    

    
  }


?>

<script>
    function refreshPage() {
        location.reload();
    }
    </script>


<body>
<div class="wrapper">
    <?php 
    include "sidebar.php";
    include "database/database.php";
    include "database/data.php";
    ?>

    <div class="main">
        <nav class="navbar navbar-expand px-3 border-bottom">
            <button class="btn" id="sidebar-toggle" type="button">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse navbar">
                <ul class="navbar-nav">
                <div class="mb-3" style="margin-right:30px">
                <h4 style="font-size:25px">ပစ္စည်းပြောင်းရန်</h4>
                </div>

                    <li class="nav-item dropdown">
                        <a href="#" data-bs-toggle="dropdown" class="nav-icon pe-md-0">
                            <img src="image/logo.png" class="avatar img-fluid rounded" alt="">
                        </a>
                        <?php include "logo_profile.php";?>
                    </li>
                </ul>
            </div>
        </nav>

        <main class="content px-3 py-2">

            <div class="container-fluid">


                <div class="row">

                    <div class="col-sm-4" style="background-color:#19242e;border-radius:20px;color:orange;margin-bottom:20px">

                    <form id="myForm" action="product_change.php" method="POST" style="margin-top:20px;margin-left:20px" enctype="multipart/form-data">
                    
                    <table style="border:none;">

                    <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi" style="font-size:20px">Barcode:</label></th>
                            <th>
                            <div style="display:flex;">
                                <input type="text" class="form-control" name="barcode" id="barcodeInput" placeholder=""  style="width:80%" autofocus>
                                <button type="button" id="start-scan-btn" class="btn btn-outline-warning" style="margin-left:10px">Scan</button>
                            </div>
                            </th>
                            <!-- <th><button type="button" name="print" id="print" class="btn btn-outline-warning">Print</button></th> -->
                        </tr>
                        
                        <script>
                            document.addEventListener('DOMContentLoaded', () => {
                            const video = document.getElementById('barcode-scanner');
                            const barcodeInput = document.getElementById('barcodeInput');
                            const startScanButton = document.getElementById('start-scan-btn');
                            let stream = null; // To store the camera stream

                            startScanButton.addEventListener('click', async () => {
                                try {
                                stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
                                video.srcObject = stream;

                                video.addEventListener('loadedmetadata', () => {
                                    video.play();
                                    detectBarcode();
                                });
                                } catch (error) {
                                console.error('Error accessing camera:', error);
                                }
                            });

                            async function detectBarcode() {
                                const barcodeDetector = new BarcodeDetector();
                                
                                try {
                                const barcodes = await barcodeDetector.detect(video);
                                if (barcodes.length > 0) {
                                    const detectedBarcode = barcodes[0].rawValue;
                                    barcodeInput.value = detectedBarcode;
                                    // Close the camera stream
                                    closeCamera();
                                } else {
                                    setTimeout(detectBarcode, 200); // Check again after 200ms
                                }
                                } catch (error) {
                                console.error('Barcode detection error:', error);
                                }
                            }

                            function closeCamera() {
                                if (stream) {
                                const tracks = stream.getTracks();
                                tracks.forEach(track => track.stop());
                                video.srcObject = null;
                                }
                            }
                            });
                        </script>

<?php 
                        $data = [];

                        // SQL query to fetch product names
                        $sql = "SELECT product_name FROM ".$product."";
                        $result_inner = $connection->query($sql);
                        
                        // Check if the query returned any results
                        if ($result_inner && $result_inner->num_rows > 0) {
                            while ($row_inner = $result_inner->fetch_assoc()) {
                                // Append each product name to the $data array
                                $data[] = $row_inner['product_name'];
                            }
                        }
                        
                        // Convert PHP array to a JSON array for use in JavaScript
                        $jsonData = json_encode($data);
                        ?>

                        <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> ပစ္စည်းအမည်:</label></th>
                            <th><input type="text" class="form-control"  id="product_name" name="product_name" placeholder="barcode သုံးပါကထည့်ရန်မလို" autocomplete="off" onkeyup="showSuggestions(this.value)"></th>
                            <div id="suggestions"></div>
                        </tr>
                        <!-- Scrip for product -->
                        <script>
                            // Convert PHP data to JavaScript
                            const data = <?php echo $jsonData; ?>;

                            // Function to filter and display suggestions
                            function showSuggestions(input) {
                                const suggestionsDiv = document.getElementById('suggestions');
                                suggestionsDiv.innerHTML = '';  // Clear suggestions

                                // Check if input is not empty
                                if (input.length > 0) {
                                    const filteredData = data.filter(item => item.toLowerCase().startsWith(input.toLowerCase()));

                                    // Display matching results
                                    if (filteredData.length > 0) {
                                        filteredData.forEach(item => {
                                            const suggestionItem = document.createElement('div');
                                            suggestionItem.textContent = item;
                                            suggestionItem.onclick = function() {
                                                document.getElementById('product_name').value = item;
                                                suggestionsDiv.style.display = 'none';
                                            };
                                            suggestionsDiv.appendChild(suggestionItem);
                                        });
                                        suggestionsDiv.style.display = 'block';  // Show suggestions
                                    } else {
                                        suggestionsDiv.style.display = 'none';  // Hide if no matches
                                    }
                                } else {
                                    suggestionsDiv.style.display = 'none';  // Hide if input is cleared
                                }
                            }
                        </script>

          
                        <tr style="height: 50px;">
                        <th><label for="package_price" alt="hi">ပြောင်းလိုသည့်:</label></th>
                        <th style="display:flex;">
                            <input type="text" class="form-control" id="data_1" name="amount"  value="1">
                            <select name="change_type" id="currency_package_price" class="form-control ms-3">        
                                <option value="unit">ကဒ်</option>
                                <option value="pieces">ဗူး</option>
                            </select>
                        </th>
                        </tr>

                        </tr>

                    </table>


                    <div style="margin-top: 20px; display: flex; justify-content: center;" class="container-fluid">
                        <button type="submit" name="add" class="btn btn-outline-warning" style="margin: 10px;width:100%">ပြောင်းရန်</button>
                        <!-- <button type="button" class="btn btn-outline-danger" style="margin: 10px;" data-toggle="modal" data-target="#infoModal">ပုံပြောင်းရန်</button> -->
                    </div>

                    </form>

                    <script>
                    document.getElementById('myForm').addEventListener('keydown', function(event) {
                        if (event.key === 'Enter') {
                        event.preventDefault(); // Prevent the default action (form submission)
                        }
                    });
                    </script>

                    </div>
                
                <!-- Table Element -->
                <div class="col-sm-8">

                <div class="card-header gx-5">
                        <form class="d-flex flex-row-reverse ">
                        <div class="col-auto" style="margin-left:10px">
                            <input type="text" class="form-control" id="searchInput" placeholder="Search">
                        </div>
                        <div class="col-auto">
                            <button type="submit" class="btn btn-primary mb-3"><i class="fa-solid fa-magnifying-glass"></i></button>
                        </div>
                        </form>
                        </div>

                        <div class="scrollable-table" style="height:60vh;">
                            <table class="table table-bordered table-hover" style="color:white;font-size:18px;"  id="dataTable">
                            <thead style="background-color:#19242e">
                            <tr>

                            <tr>
                            <th scope="col" rowspan="2">no</th>
                            <th scope="col" rowspan="2">barcode</th>
                            <th scope="col" rowspan="2">ပစ္စည်းအမည်</th>
                            <th scope="col" rowspan="2">အမျိုးအစား</th>
                            <th scope="col" rowspan="2" style="color:#ACE1AF">မူရင်းကဒ်</th>
                            <th scope="col" rowspan="2" style="color:#ACE1AF">မူရင်းဗူး</th>
                            <th scope="col" colspan="3" style="color:#FFA62F">ပစ္စည်းလက်ကျန်</th>
                        </tr>
                        <tr>
                            <th scope="col" style="color:#FFA62F">ဖာ</th>
                            <th scope="col" style="color:#FFA62F">ကဒ်</th>
                            <th scope="col" style="color:#FFA62F">ဗူး</th>
                        </tr>
                        </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $sql = "Select * from ".$product." where delete_d='0' order by id desc limit 50";
                                $result = mysqli_query($connection, $sql);
                                if ($result) {
                                    while ($row = mysqli_fetch_assoc($result)) {
                                        echo '<tr>
                                        <td contenteditable="true" class="fixed-column">' . htmlspecialchars($row['id']) . '</td>       
                                        <td contenteditable="true" class="fixed-column-2">' . htmlspecialchars($row['barcode']) . '</td>
                                        <th scope="row" contenteditable="true" class="fixed-column-3">' . htmlspecialchars($row['product_name']).'</th>
                                        <td contenteditable="true" class="fixed-column-3">' . htmlspecialchars($row['type']) . '</td>  
                                        <td contenteditable="true">' . htmlspecialchars($row['unit']) . '</td>
                                        <td contenteditable="true">' . htmlspecialchars($row['pieces']) . '</td>             
                                        <td contenteditable="true">' . number_format($row['package_exist']) . '</td>
                                        <td contenteditable="true">' . number_format($row['unit_exist']) . '</td>
                                        <td contenteditable="true">' . number_format($row['pieces_exist']) . '</td>                                                                                                               
                                        </tr>';
                                    }
                                }
                                    mysqli_free_result($result);
                                
                                ?>
                            </tbody>
                                
                            </table>


<script>
    $(document).ready(function() {
        $('#infoModal').on('hidden.bs.modal', function () {
            location.reload();
        });
    });
</script>

                        <!-- Search for js code -->
                        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                            <script> 
                            $(document).ready(function() {
                                $("#searchInput").on("keyup", function() {
                                    var value = $(this).val().toLowerCase();
                                    
                                    $("#dataTable tbody tr").filter(function() {
                                        $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                                    });
                                });
                            });
                            </script>

                    </div>
                </div>

                 </div>

                 <!-- Table View -->
                 <div class="row" style="margin-top:180px">
                  
                  <!-- Table Element -->
                  <div class="container-fluid">


                  <div class="container-fluid" style="margin-bottom: 20px;">
                      <form>
                      <div class="row">
                      <div class="col-sm-2 mb-2">
                          <div class="select-container">
                              <input type="text" class="form-control" id="accountInput" name="voucher" onchange="filterTable()" placeholder="Enter Voucher No">
             
                          </div>
                      </div>


                      <div class="col-sm-2 mb-2">
                          <div class="select-container">
                              <select name="product_type" id="dayInput" onchange="filterTable()" class="form-control">
                                  <option value="">Select Day</option>
                                  <option value="1">1</option>
                                  <option value="2">2</option>
                                  <option value="3">3</option>
                                  <option value="4">4</option>
                                  <option value="5">5</option>
                                  <option value="6">6</option>
                                  <option value="7">7</option>
                                  <option value="8">8</option>
                                  <option value="9">9</option>
                                  <option value="10">10</option>
                                  <option value="11">11</option>
                                  <option value="12">12</option>
                                  <option value="13">13</option>
                                  <option value="14">14</option>
                                  <option value="15">15</option>
                                  <option value="16">16</option>
                                  <option value="17">17</option>
                                  <option value="18">18</option>
                                  <option value="19">19</option>
                                  <option value="20">20</option>
                                  <option value="21">21</option>
                                  <option value="22">22</option>
                                  <option value="23">23</option>
                                  <option value="24">24</option>
                                  <option value="25">25</option>
                                  <option value="26">26</option>
                                  <option value="27">27</option>
                                  <option value="28">28</option>
                                  <option value="29">29</option>
                                  <option value="30">30</option>
                                  <option value="31">31</option>
                              </select>
                              <!-- <i class="fas fa-chevron-down"></i> -->
                          </div>
                      </div>

                      <div class="col-sm-2 mb-2">
                          <div class="select-container">
                              <select name="product_type" id="monthInput" onchange="filterTable()" class="form-control">
                                  <option value="">Select Month</option>
                                  <option value="1">January-1</option>
                                  <option value="2">February-2</option>
                                  <option value="3">March-3</option>
                                  <option value="4">April-4</option>
                                  <option value="5">May-5</option>
                                  <option value="6">June-6</option>
                                  <option value="7">July-7</option>
                                  <option value="8">August-8</option>
                                  <option value="9">September-9</option>
                                  <option value="10">October-10</option>
                                  <option value="11">November-11</option>
                                  <option value="12">December-12</option>
                              </select>
                              <!-- <i class="fas fa-chevron-down"></i> -->
                          </div>
                      </div>

                      <div class="col-sm-2 mb-2">
                          <div class="select-container">
                              <select name="product_type" id="yearInput" onchange="filterTable()" class="form-control">
                                  <option value="">Select Year</option>
                                  <option value="2023">2023</option>';
                                  <option value="2024">2024</option>';
                                  <option value="2025">2025</option>';
                                  <option value="2026">2026</option>';
                                  <option value="2027">2027</option>';
                                  <option value="2028">2028</option>';
                                  <option value="2029">2029</option>';
                                  <option value="2030">2030</option>';
                                  <option value="2031">2031</option>';
                                  <option value="2032">2032</option>';
                                  <option value="2033">2033</option>';
                                  <option value="2034">2034</option>';
                                  <option value="2035">2035</option>';
                              </select>
                              <!-- <i class="fas fa-chevron-down"></i> -->
                          </div>
                      </div>

                      <div class="col-sm-2">
                      <div class="select-container">
                      <!-- <button type="submit" name="baht" class="btn btn-outline-success" style="margin: 10px;" onclick="refreshPage()">Show All</button> -->
                      <button type="submit" class="btn btn-outline-success" onclick="refreshPage()">Show All</button>
                  </div>

                      </form>
                  </div>

                  <script>
                      function refreshPage() {
                          location.reload();
                      }
                  </script>

                  </div>

                      
                  <div class="col" style="margin-top:20px;">

                  <div class="scrollable-table" style="height:60vh;">
                  <table class="table table-bordered table-hover" style="color:white;font-size:18px;"  id="myTable">
                  <thead style="background-color:#19242e">
                          <tr>
                          <th scope="col">id</th>
                          <th scope="col">barcode</th>
                          <th scope="col">ပစ္စည်းအမည်</th>
                          <th scope="col">ပြောင်းသည့် ကဒ်ပမာဏ</th>
                          <th scope="col">ပြောင်းသည့် ဗူးပမာဏ</th>
                          <th scope="col">ပြောင်းသူအမည်</th>
                          <th scope="col">Day</th>
                          <th scope="col">Month</th>
                          <th scope="col">Year</th>
                          <th scope="col">ဖျက်ရန်</th>
                          </tr>
                          </thead>
                              <tbody>
                                  <?php 
                                //   $sql = "SELECT * FROM ".$cargo." WHERE browser_id='$b_id'";
                                //   $result = $connection->query($sql);
                                //   if ($result->num_rows > 0) {
                                //       $row = $result->fetch_assoc(); // Fetch the row here
                                //       $cargo_data = $row["cargo_name"];
                                  
                                      $sql = "SELECT *,DAY(date) as date_day, MONTH(date) as date_month, YEAR(date) as date_year FROM ".$product_change." ORDER BY id DESC";
                                      $result = mysqli_query($connection, $sql);
                                  
                                      if ($result) {
                                          while ($row = mysqli_fetch_assoc($result)) {
                                                                              
                                              echo '<tr>
                                                  <td>' . htmlspecialchars($row['id']) . '</td>
                                                  <td style="display:none;">' . htmlspecialchars($row['name']) . '</td>
                                                  <th scope="row">' . htmlspecialchars($row['name']) . '</td>

                                                  <td>' . htmlspecialchars($row['barcode']) . '</td>
                                             
                                                  <td>' . htmlspecialchars($row['unit']) . '</td>
                                                  <td>' . htmlspecialchars($row['pieces']) . '</td>
                                                  <td>' . htmlspecialchars($row['user_name']) . '</td>
                                                  <td>' .($row['date_day']) . '</td>
                                                  <td>' .($row['date_month']) . '</td>
                                                  <td>' .($row['date_year']) . '</td>
                                                  <td><button type="submit" class="btn btn-danger" onclick="deleteRow(this)">Delete</button></td>   
                                              </tr>';
                                          }
                                          mysqli_free_result($result);
                                      } else {
                                          // Handle query error
                                         
                                      }
                                //   } else {
                                //       // Handle case when no rows are found
                                    
                                //   }
                                  
                          
                                  ?>
                                  
                                  <style>
                                      .near-today {
                                          color: red;
                                          font-weight: bold;
                                      }
                                  </style>

                                  <!-- Delete Data -->
                          <script>
                          function deleteRow(button) {
                          const row = button.parentNode.parentNode;
                          const id = row.cells[0].textContent; // Assuming the Product ID is in the first column (index 0)
                          console.log(id)
                          // Send the id to the backend PHP script using AJAX for deletion
                          const xhr = new XMLHttpRequest();
                          xhr.open('POST', 'product_change.php', true);
                          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                          xhr.onreadystatechange = function() {
                              if (xhr.readyState === XMLHttpRequest.DONE) {
                              if (xhr.status === 200) {
                                  row.parentNode.removeChild(row); // Remove the row from the table on successful deletion
                                  alert('Data deleted successfully!');
                                  location.reload();

                              } else {
                                  alert('Error deleting data. Please try again.');
                              }
                              }
                          };
                          xhr.send('id=' + encodeURIComponent(id));
                          }
                      </script>

                      <script>
                        function filterTable() {
                                  var accountInput, dayInput, monthInput, yearInput;
                                  var filterAccount, filterDay, filterMonth, filterYear;
                                  var table, tr, tdAccount, tdDay, tdMonth, tdYear, tdTotal, total, i;

                                  accountInput = document.getElementById("accountInput");
                                  dayInput = document.getElementById("dayInput");
                                  monthInput = document.getElementById("monthInput");
                                  yearInput = document.getElementById("yearInput");

                                  filterAccount = accountInput.value.toUpperCase();
                                  filterDay = dayInput.value;
                                  filterMonth = monthInput.value;
                                  filterYear = yearInput.value;

                                  table = document.getElementById("myTable");
                                  tr = table.getElementsByTagName("tr");
                                  total = 0;

                                  for (i = 1; i < tr.length; i++) {
                                      tdAccount = tr[i].getElementsByTagName("td")[1]; // Account/Product column
                                      tdDay = tr[i].getElementsByTagName("td")[8]; // Day column
                                      tdMonth = tr[i].getElementsByTagName("td")[9]; // Month column
                                      tdYear = tr[i].getElementsByTagName("td")[10]; // Year column
                                      tdTotal = tr[i].getElementsByTagName("td")[5]; // Total column

                                      if (tdAccount && tdDay && tdMonth && tdYear && tdTotal) {
                                          var accountMatch = filterAccount === "" || tdAccount.textContent.toUpperCase().indexOf(filterAccount) > -1;
                                          var dayMatch = filterDay === "" || tdDay.textContent === filterDay;
                                          var monthMatch = filterMonth === "" || tdMonth.textContent === filterMonth;
                                          var yearMatch = filterYear === "" || tdYear.textContent === filterYear;

                                          if (accountMatch && dayMatch && monthMatch && yearMatch) {
                                              tr[i].style.display = "";
                                              total += parseFloat(tdTotal.textContent || tdTotal.innerText);
                                          } else {
                                              tr[i].style.display = "none";
                                          }
                                      }
                                  }
                             
                              }
                      </script>
                                  

                              
   
                              </tbody>
                          </table>

                          <!-- Search for js code -->
                          <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                          <script> 
                          $(document).ready(function() {
                              $("#searchInput").on("keyup", function() {
                                  var value = $(this).val().toLowerCase();
                                  
                                  $("#dataTable tbody tr").filter(function() {
                                      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                                  });
                              });
                          });
                          </script>
                      </div>
                  </div>
                  </div>
            </div>

        </main>


        <a href="#" class="theme-toggle">
            <i class="fa-regular fa-moon"></i>
            <i class="fa-regular fa-sun"></i>
        </a>
        <footer class="footer">
            <div class="container-fluid">
                <div class="row text-muted">
                    <div class="col-6 text-start">
                        <p class="mb-0">
                            <a href="#" class="text-muted">
                                <?php 
                                    include "version.php";
                                ?>
                            </a>
                        </p>
                    </div>
                    <div class="col-6 text-end">
                        <ul class="list-inline">
                            <li class="list-inline-item">
                                <a href="#" class="text-muted">Contact</a>
                            </li>
                            <li class="list-inline-item">
                                <a href="#" class="text-muted">About Us</a>
                            </li>
                            <li class="list-inline-item">
                                <a href="#" class="text-muted">Terms</a>
                            </li>
                            <li class="list-inline-item">
                                <a href="#" class="text-muted">Booking</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </footer>
    </div>
</div>

<!-- Number Format -->
<script>
    function formatNumber() {
        const inputField = document.getElementById('package_price');
        let value = inputField.value;

        // Remove any non-numeric characters (except for decimal points)
        value = value.replace(/[^0-9.]/g, '');

        // Format the number
        const formattedValue = new Intl.NumberFormat().format(value);

        // Set the formatted value back to the input field
        inputField.value = formattedValue;
    }
</script>


<!-- <script src="lat_li.js"></script> -->
<!-- get data auto from input barcode/banking -->
<!-- <script>
    document.addEventListener('DOMContentLoaded', (event) => {
const barcodeInput = document.getElementById('barcodeInput');
const bankingInput = document.getElementById('bankingInput');
const outputDiv = document.getElementById('output');

// Simulate a barcode scanner by listening for input events
barcodeInput.addEventListener('input', handleBarcodeInput);

let barcode = '';
let timeout;

function handleBarcodeInput(event) {
    clearTimeout(timeout);
    
    // Check for input data and append to barcode
    barcode += event.data || event.target.value; 
    
    // Clear the input field
    event.target.value = '';

    // Wait for a short period to determine if input is complete
    timeout = setTimeout(() => {
        processBarcode(barcode);
        barcode = ''; // Reset barcode
    }, 100); // Adjust timeout as needed
}

async function processBarcode(barcode) {
    // Get banking input value
    const bankingData = bankingInput.value;

    // Display the processed barcode and banking data on the page
    outputDiv.innerHTML = `Processed Barcode: ${barcode} <br> Banking Data: ${bankingData}`;
    console.log(`Processed Barcode: ${barcode}`);
    console.log(`Banking Data: ${bankingData}`);

    // Send the barcode and banking data to the server
    try {
        const response = await fetch('lat_li.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 
                barcode: barcode,
                bankingData: bankingData
            })
        });

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

        const responseData = await response.json();
        console.log('Server response:', responseData);
    } catch (error) {
        console.error('Error sending data:', error);
    }
}
});
</script>
<div id="output"></div>


<?php
// header('Content-Type: application/json');
// $input = file_get_contents('php://input');
// $data = json_decode($input, true);

// if ($data && isset($data['barcode']) && isset($data['bankingData'])) {
//     // Process the barcode and banking data here
//     $barcode = $data['barcode'];
//     $bankingData = $data['bankingData'];

//     include 'database/database.php';

//     // Log received data for debugging purposes
//     error_log("Received barcode: " . $barcode);
//     error_log("Received bankingData: " . $bankingData);

//     $query = "UPDATE imv_account SET account='$barcode', amount='$bankingData' WHERE id='1'";
//     if ($connection->query($query)) {
//         // Example response
//         echo json_encode([
//             'status' => 'success', 
//             'receivedBarcode' => $barcode,
//             'receivedBankingData' => $bankingData
//         ]);
//     } else {
//         die("ERROR: Query failed. " . $connection->error);
//     }
// } else {
//     echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
// }


?> -->


<?php 

function generateUniqueBrowserId()
{
    $randomString = bin2hex(random_bytes(16));
    $timestamp = time();

    return $randomString . $timestamp;
}

?>

    


 
<script src="js/script.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>

</html>
