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



<?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_rate.php";


if (isset($_POST['change_currency'])) {

    $rate_data = $_POST['rate'];
    $currency_buy = $_POST['currency'];
    $profit = $_POST['profit'];

    if ($profit==''){ 

        if ($currency_buy == 'baht'){ 

            $query = "UPDATE $rate SET baht = '$rate_data'";
            if (mysqli_query($connection, $query)) {
                // echo "Update successful";
            } else {
                // echo "Error: " . mysqli_error($connection);
            }
    
        } else if($currency_buy == 'yuan'){ 
    
            $query = "UPDATE $rate SET yuan = '$rate_data'";
            if (mysqli_query($connection, $query)) {
                // echo "Update successful";
            } else {
                // echo "Error: " . mysqli_error($connection);
            }
    
    
    
        } else if($currency_buy == 'dollar'){ 
    
            $query = "UPDATE $rate SET dollar = '$rate_data'";
            if (mysqli_query($connection, $query)) {
                // echo "Update successful";
            } else {
                // echo "Error: " . mysqli_error($connection);
            }
        } 
    
    
        $query = "UPDATE $product SET
              rate = '$rate_data'
              WHERE delete_d = '0' AND 
              currency_buy = '$currency_buy'";
    
                if (mysqli_query($connection, $query)) {
                    
                } else {
                    echo "Error: " . $query . "<br>" . mysqli_error($connection);
                }
    
            //     function roundUpToNearestHundred($number) {
            //         return ceil($number / 100) * 100;
            //     }
    
            //     $sql = "SELECT * FROM ".$rate."";
            //     $result = $connection->query($sql);
            //     if ($result && $result->num_rows > 0) {
            //     while ($row = $result->fetch_assoc()) {
            //         $profit = $row['profit']; 
                    
            //         $sql = "SELECT * FROM ".$product."";
            //         $result = $connection->query($sql);
                    
            //         if ($result && $result->num_rows > 0) {
            //             while ($row = $result->fetch_assoc()) {
            //                 $product_name = $row['product_name'];
            //                 $buy = $row['buy'];
            //                 $trans = $row['trans'];
            //                 $unit = $row['unit'];
            //                 $pieces = $row['pieces'];
            //                 $rate = $row['rate'];
                    
            //                 $package_price = ((($buy*$rate)*($profit/100))+($buy*$rate)+$trans);
            //                 $unit_price = $package_price / $unit;
            //                 $pieces_price = $unit_price / $pieces;
                    
            //                 $round_package_price = roundUpToNearestHundred($package_price);
            //                 $round_unit_price = roundUpToNearestHundred($unit_price);
            //                 $round_pieces_price = roundUpToNearestHundred($pieces_price);
                    
                    
            //                 $query = "UPDATE $product SET 
            //                         round_package_price = '$round_package_price',
            //                         round_unit_price = '$round_unit_price',
            //                         round_pieces_price = '$round_pieces_price'
            //                         WHERE delete_d = '0' AND currency_buy = '$currency_buy' AND product_name = '$product_name'";
                    
            //                 if (mysqli_query($connection, $query)) {
            //                     header('Location: product_rate.php');
            //                 } else {
            //                     echo "Error: " . $query . "<br>" . mysqli_error($connection);
            //                 }
            //             }
            //         } else {
            //             echo "No records found or error in query: " . $connection->error;
            //         }
            //     }
            // }
        header('location:product_rate.php');

    }else{ 

    // $query = "UPDATE $rate SET profit = '$profit'";
    //     if (mysqli_query($connection, $query)) {
    //         // echo 'none';
    //     } else {
    //         // echo "Error: " . mysqli_error($connection);
    //     }
    //     $query = "UPDATE $product SET profit = '$profit'";
    
    //             if (mysqli_query($connection, $query)) {
                    
    //             } else {
    //                 echo "Error: " . $query . "<br>" . mysqli_error($connection);
    //             }
    
    //             function roundUpToNearestHundred($number) {
    //                 return ceil($number / 100) * 100;
    //             }
    
    //             $sql = "SELECT * FROM ".$rate."";
    //             $result = $connection->query($sql);
    //             if ($result && $result->num_rows > 0) {
    //             while ($row = $result->fetch_assoc()) {
    //                 $profit = $row['profit']; 
                    
    //                 $sql = "SELECT * FROM ".$product."";
    //                 $result = $connection->query($sql);
                    
    //                 if ($result && $result->num_rows > 0) {
    //                     while ($row = $result->fetch_assoc()) {
    //                         $product_name = $row['product_name'];
    //                         $buy = $row['buy'];
    //                         $trans = $row['trans'];
    //                         $unit = $row['unit'];
    //                         $pieces = $row['pieces'];
    //                         $rate = $row['rate'];
                    
    //                         $package_price = ((($buy*$rate)*($profit/100))+($buy*$rate)+$trans);
    //                         $unit_price = $package_price / $unit;
    //                         $pieces_price = $unit_price / $pieces;
                    
    //                         $round_package_price = roundUpToNearestHundred($package_price);
    //                         $round_unit_price = roundUpToNearestHundred($unit_price);
    //                         $round_pieces_price = roundUpToNearestHundred($pieces_price);
                    
                    
    //                         $query = "UPDATE $product SET 
    //                                 round_package_price = '$round_package_price',
    //                                 round_unit_price = '$round_unit_price',
    //                                 round_pieces_price = '$round_pieces_price'
    //                                 WHERE delete_d = '0' AND currency_buy = '$currency_buy' AND product_name = '$product_name'";
                    
    //                         if (mysqli_query($connection, $query)) {
    //                             header('Location: product_rate.php');
    //                         } else {
    //                             echo "Error: " . $query . "<br>" . mysqli_error($connection);
    //                         }
    //                     }
    //                 } else {
    //                     echo "No records found or error in query: " . $connection->error;
    //                 }
    //             }
    //         }
    //     header('location:product_rate.php');
    }
 

    
    }


        

  
?>

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


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

                        <tr style="height: 50px;">
                            <th><label for="package_price" alt="hi">ငွေဈေး:</label></th>
                            <th style="display:flex;">
                                <input type="text" value="1" class="form-control" id="package_price" name="rate" placeholder="Enter Price" maxlength="20" oninput="validateNumber(this)">

                                <select name="currency" id="currency_package_price" class="form-control ms-3">        
                                    <option value="baht">ဘတ်</option>
                                    <option value="yuan">ယွမ်</option>
                                    <option value="dollar">ဒေါ်လာ</option>
                                </select>
                            </th>
                        </tr>

                        <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="profit" placeholder="Profit" maxlength="20" oninput="validateNumber(this)">
                                <select id="currency_package_price" class="form-control ms-3">        
                                    <option value="baht">% (Percent)</option>
                                </select>
                            </th>
                        </tr>
                        
                        <script>
    function validateNumber(input) {
        input.value = input.value.replace(/[^0-9.]/g, ''); // Only allow digits and dot
        
        // Ensure there's only one dot
        const parts = input.value.split('.');
        if (parts.length > 2) {
            input.value = parts[0] + '.' + parts.slice(1).join(''); // Keep only the first dot
        }
    }
</script>


                
                            </tr>

                        </table>

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

                            <tr>
                                <th style="margin-top:20px;text-align:center;" scope="col" colspan="3"><a style="color:#ccc8c8;font-size:15px;"><br>(ငွေဈေးတစ်ခုတည်း ပြောင်းမည်ဆိုပါက <br>အမြတ်ထည့်ရန်မလို)</a></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">ဘတ်</th>
                            <th scope="col">ယွမ်</th>
                            <th scope="col">ဒေါ်လာ</th>
                            <th scope="col">အမြတ် %</th>
                            </tr>
                            </thead>
                                <tbody>
                                    <?php 
                                    
                                    $sql = "Select * from ".$rate."";
                                    $result = mysqli_query($connection, $sql);
                                    if ($result) {
                                        while ($row = mysqli_fetch_assoc($result)) {
                                            echo '<tr>
                                                <td>' . $row['id']. '</td>
                                                <td>' . $row['baht']. '</td>
                                                <td>' . $row['yuan'] . '</td>
                                                <td>' . $row['dollar'] . '</td>
                                                <td>' . $row['profit'] . '</td>
                                            </tr>';
                                        }
                                        mysqli_free_result($result);
                                    }

                                    ?>
     
                                </tbody>
                            </table>



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