<!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>
        /* 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>



<?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 "login_check.php";
include "cal_pro_remain.php";


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

    if ($barcode != '' || $product_name != ''){ 

    }else{ 
        $supplier = $_POST['supplier'];
        $payment = $_POST['payment'];
        $banking_data = $_POST['banking'];
        $buy = $_POST['buy'];
        $currency = $_POST['currency'];
        $type = $_POST['type'];
        $refill_amount = $_POST['refill_amount'];
        $voucher = $_POST['voucher'];
        $date = $_POST['date'];
        $insert_date = $_POST['insert_date'];

        if ($barcode != '') {
            $sql = "SELECT * FROM ".$product." WHERE (barcode='$barcode' OR barcode_1='$barcode') AND delete_d='0'";
        } else {
            $sql = "SELECT * FROM ".$product." WHERE product_name='$product_name' AND delete_d='0'";
        }
    

        if ($payment == 'pay'){ 
 
            $sql = "SELECT * FROM ".$banking." WHERE type='$banking_data'";
            $result = mysqli_query($connection, $sql);
            if ($result) {
                    while ($row = mysqli_fetch_assoc($result)) {

                        

                    $remain = $row['remain'];
                    $total = $refill_amount * $buy;

                    if ($remain >= $total){ 

                        $sql = "SELECT * FROM ".$product." where barcode='$barcode' or barcode_1='$barcode' and delete_d='0'";
                        $result = $connection->query($sql);
                        if ($result && $result->num_rows > 0) {
                        while ($row = $result->fetch_assoc()) {
                            $product_name = $row['product_name'];

                            $sql = "SELECT * FROM ".$cargo." WHERE browser_id='$b_id'";
                            $result = $connection->query($sql);
                            if ($result->num_rows > 0) {
                                while ($row = $result->fetch_assoc()) {
                                    $cargo_data = $row['cargo_name'];
                            
                                    $sql = "INSERT INTO ".$cargo_data."_refill (barcode, product_name, supplier, payment,banking,buy,currency,type,qty,total,voucher,date_1,date,delete_d)
                                    VALUES ('$barcode','$product_name','$supplier','$payment','$banking_data','$buy','$currency','$type','$refill_amount','$total','$voucher','$insert_date','$date','0')";
                                    if (mysqli_query($connection, $sql)) {
                                        header('location:product_refill.php');
                                    } else {
                                        echo "Error: " . $sql . " " . mysqli_error($connection);
                                    }
                        }
                    }

                        }
                    } else { 
                        echo '<script>alert("Product not Found") ;</script>';
                    }
    
    
                    }
                }
            }

        } else { 
    
            $total = $refill_amount * $buy;
            $sql = "SELECT * FROM ".$product." where barcode='$barcode' or barcode_1='$barcode' and delete_d='0'";
            $result = $connection->query($sql);
            if ($result && $result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $product_name = $row['product_name'];

                $sql = "SELECT * FROM ".$cargo." WHERE browser_id='$b_id'";
                $result = $connection->query($sql);
                if ($result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {
                        $cargo_data = $row['cargo_name'];

                        $sql = "INSERT INTO ".$cargo_data."_refill (barcode, product_name, supplier, payment,banking,buy,currency,type,qty,total,voucher,date_1,date,delete_d)
                        VALUES ('$barcode','$product_name','$supplier','$payment','$banking_data','$buy','$currency','$type','$refill_amount','$total','$voucher','$insert_date','$date','0')";
                        if (mysqli_query($connection, $sql)) {
                            header('location:product_refill.php');
                        
                        } else {
                            echo "Error: " . $sql . " " . mysqli_error($connection);
                        }
            }
        }
            }
        } else { 
            echo '<script>alert("Product not Found") ;</script>';
        }
    
        }
    }
}


    // delete Data
    if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["id"])) {
        $id = $connection->real_escape_string($_POST["id"]);
        echo "Received id: " . $id;
    
        $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"];

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


<body>
    <div class="wrapper">
        <?php 
        include "sidebar.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="mb-3" style="position: relative;">
                
                    
                </div>


                    <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_refill.php" method="POST" style="margin-top:20px;margin-left:20px">
                        <table style="border:none;">


                        <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> 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="package_price" name="buy" placeholder="" >
                                <select name="currency" id="currency_package_price" class="form-control ms-3">        
                                    <option value="kyat">ကျပ်</option>
                                    <option value="baht">ဘတ်</option>
                                    <option value="yuan">ယွမ်</option>
                                </select>
                        
                            </th>
                            </tr>


                            <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> အရေအတွက်:</label></th>
                            <div >
                            <th style="display:flex;">
                            <input type="text" class="form-control"  name="refill_amount" placeholder="" value="1">
                                <select name="type" id="currency_package_price" class="form-control ms-3">        
                                <option value="ဖာ">ဖာ</option>
                                <option value="ကဒ်">ကဒ်</option>
                                <option value="ဗူး/ခု">ဗူး/ခု</option>
                                </select>
                            </th>
                            </div>
                        </tr>


                            <tr style="height: 50px;">
                                <th> <label for="pwd">ယူသည့်ဆိုင်:</label></th>
                                <th>
                                    <select name="supplier" class="form-control">
                                        <?php
                                        $sql = "SELECT * FROM ".$supplier."";
                                        $result = $connection->query($sql);
                                        if ($result && $result->num_rows > 0) {
                                            while ($row = $result->fetch_assoc()){
                                                $name = $row['name']; // Database
                                                echo '
                                                <option value="' . $name . '">' . $name . '</option>
                                                ';
                                            }
                                        }
                                        ?>
                                    </select>
                                </th>
                            </tr>

                            <tr style="height: 50px;">
                                <th> <label for="pwd" alt="hi"> ငွေချေ:</label></th>
                                <th><select name="payment" id="payment" class="form-control">  
                                <option value="pay">လက်ငင်း</option>
                                <option value="debt">အကြွေး</option>  
                                
                                </select></th>
                            </tr>

                            <tr style="height: 50px;">
                                <th> <label for="pwd">ငွေချေဘဏ်:</label></th>
                                <th>
                                    <select name="banking" class="form-control">
                                        <?php
                                        $sql = "SELECT * FROM ".$banking."";
                                        $result = $connection->query($sql);
                                        if ($result && $result->num_rows > 0) {
                                            while ($row = $result->fetch_assoc()){
                                                $name = $row['type']; // Database
                                                echo '
                                                <option value="' . $name . '">' . $name . '</option>
                                                ';
                                            }
                                        }
                                        ?>
                                    </select>
                                </th>
                            </tr>

                            <tr style="height: 50px;">
                                <th> <label for="pwd" alt="hi"> Voucher:</label></th>
                                <th><input type="text" class="form-control" id="package_price" name="voucher" placeholder=""></th>
                            </tr>

                            <?php
                            $today = date("Y-m-d");

                            echo '<tr style="height: 50px;">
                                <th> <label for="pwd" alt="hi">ဖြည့်ရက်:</label></th>
                                <th><input type="date" class="form-control"  name="insert_date" value='.$today.'></th>
                            </tr>';

                            echo '<tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi">ကုန်ဆုံးရက်:</label></th>
                            <th><input type="date" class="form-control"  name="date" value='.$today.'></th>
                            </tr>';
                            
                            ?>

                            <script>
                                // Function to format the date as YYYY-MM-DD
                                function formatDate(date) {
                                    const year = date.getFullYear();
                                    const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-indexed, so add 1
                                    const day = String(date.getDate()).padStart(2, '0');
                                    return `${year}-${month}-${day}`;
                                }

                                // Get today's date
                                const today = new Date();
                                // Format today's date as YYYY-MM-DD
                                const formattedDate = formatDate(today);
                                // Set the value of the date input to today's date
                                document.getElementById('voucher').value = formattedDate;
                            </script>

                            </tr>

                        </table>

               
                        <div style="margin-top: 20px;justify-content: center;" class="container-fluid">
                            <tr>
                                <th scope="col" colspan="3"> <button type="submit" name="add" class="btn btn-outline-warning" style="margin: 10px;width:90%">ပေါင်းထည့်ရန်</button></th>
                            </tr>

                            <tr>
                                <th scope="col" colspan="3"> <button type="submit" name="refresh" class="btn btn-outline-success" style="margin: 10px;width:90%" data-toggle="modal" data-target="#infoModal" onclick="refreshPage()">Refresh</button></th>
                            </tr>


                        </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>
                            <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">ဝယ်ဈေး</th>
                            <th scope="col">ငွေကြေး</th>
                            <th scope="col">အမျိုးစား</th>
                            <th scope="col">အရေအတွက်</th>
                            <th scope="col">စုစုပေါင်း</th>
                            <th scope="col">ပေါင်ချာ</th>
                            <th scope="col">ပစ္စည်းဖြည့်ရက်</th>
                            <th scope="col">ကုန်ဆုံးရက်</th>
                            <th scope="col">Delete</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 * FROM ".$cargo_data."_refill WHERE delete_d='0' ORDER BY id DESC limit 100";
                                        $result = mysqli_query($connection, $sql);
                                    
                                        if ($result) {
                                            while ($row = mysqli_fetch_assoc($result)) {
                                                $expire_date = date('Y-m-d');
                                                $row_date = $row['date'];
                                                $date1 = new DateTime($row_date);
                                                $date2 = new DateTime($expire_date);
                                                $interval = $date1->diff($date2);
                                                $days_diff = $interval->format('%a'); // Number of days difference
                                                
                                                // Determine the CSS class based on the date difference
                                                $date_class = ($days_diff <= 7) ? 'near-today' : '';
                                                
                                                echo '<tr>
                                                    <td>' . htmlspecialchars($row['id']) . '</td>
                                                    <td>' . htmlspecialchars($row['barcode']) . '</td>
                                                    <th scope="row">' . htmlspecialchars($row['product_name']) . '</td>
                                                    <td>' . htmlspecialchars($row['supplier']) . '</td>
                                                    <td>' . htmlspecialchars($row['payment']) . '</td>
                                                    <td>' . htmlspecialchars($row['banking']) . '</td>
                                                    <td>' . number_format($row['buy']) . '</td>
                                                    <td>' . htmlspecialchars($row['currency']) . '</td>
                                                    <td>' . htmlspecialchars($row['type']) . '</td>
                                                    <td>' . htmlspecialchars($row['qty']) . '</td>
                                                    <td>' . number_format($row['total']) . '</td>
                                                    <td>' . htmlspecialchars($row['voucher']) . '</td>
                                                    <td>' . htmlspecialchars($row['date_1']) . '</td>
                                                    <td class="' . htmlspecialchars($date_class) . '">' . $days_diff . '</td> 
                                                    <td><button type="submit" class="btn btn-success" 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>
                                    

                                
     
                                </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>

                            <!-- 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 tra_id to the backend PHP script using AJAX for deletion
                            const xhr = new XMLHttpRequest();
                            xhr.open('POST', 'product_refill.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>
                        </div>
                    </div>


                </div>
                </div>
                <video id="barcode-scanner" autoplay playsinline></video>
            </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>
</body>

</html>
