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

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

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


if (isset($_POST['save'])) {
    $b_id = $browserId;
    $sql = "SELECT * FROM " . $user_database . " WHERE browser_id='$b_id'";
    $result = $connection->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {

            $user_id = $row['user_name_LL'];
            $user_name = $row['user_name'];



            $sql = "DELETE FROM " . $user_id . " where seller='" . $user_name . "'";
            if ($connection->query($sql) === true) {
                echo "<script>window.location.href = 'sell_ll.php';</script>";
            } else {
            }
        }
    }
}



if (isset($_POST['update'])) {
    $b_id = $browserId;

    $sql = "SELECT * FROM " . $user_database . " WHERE browser_id='$b_id'";
    $result = $connection->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {

            $user_id = $row['user_name_LL'];
            $user_name = $row['user_name'];
            $voucher = $_POST['voucher'];
            $payment_data = $_POST['bankingData'];

            // $rate = $_POST['rate'];
            $sql = "SELECT currency FROM " . $banking . " WHERE type='$payment_data'";
            $result = $connection->query($sql);
            if ($result && $result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $currency = $row['currency'];

                    $sql = "SELECT * FROM " . $rate . "";
                    $result = $connection->query($sql);
                    if ($result && $result->num_rows > 0) {
                        while ($row = $result->fetch_assoc()) {
                            $baht = $row['baht'];
                            $yuan = $row['yuan'];
                            $dollar = $row['dollar'];
                            $kyat = $row['kyat'];
                            $profit = $row['profit'];

                            if ($currency == 'kyat') {

                                $rate = '1';
                            } else if ($currency == 'baht') {

                                $rate = $baht;
                            } else if ($currency == 'yuan') {

                                $rate = $yuan;
                            } else if ($currency_buy == 'dollar') {

                                $rate = $dollar;
                            }
                        }
                    }
                }
            } else {
                // Default rate if no matching record in the first query
                $rate = 1;
            }


            //update user sell database
            $query = "UPDATE " . $user_id . " set voucher='$voucher',banking='$payment_data',rate='$rate' where seller='$user_name'";
            if (!$connection->query($query)) {
                die("ERROR: Query failed. " . $connection->error);
            }

            //update sell database
            $sql = "SELECT tra_id,voucher FROM " . $user_id . "";
            $result = $connection->query($sql);
            if ($result && $result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $tra_id = $row['tra_id'];
                    $voucher = $row['voucher'];

                    $query = "UPDATE " . $sell_data . " set voucher='$voucher',banking='$payment_data',rate='$rate' where tra_id='$tra_id'";
                    if (!$connection->query($query)) {
                        die("ERROR: Query failed. " . $connection->error);
                    }
                }
            }
        }
    }

    echo "<script>window.location.href = 'sell_ll.php';</script>";
}


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

    $barcode = $_POST['barcode'];
    $product_name = $_POST['product_name'];

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

        $bankingData = $_POST['bankingData'];
        $typeData = $_POST['typeData'];
        $qtyData = $_POST['qtyData'];

        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'";
        }

        $result = $connection->query($sql);
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {

                $tra_id_data = new DateTime();
                $rn = rand(0, 1000);

                if ($barcode == '') {
                    $barcode = $row['barcode']; // If barcode is empty, fill it from DB
                }
                $product_name = $row['product_name'];

                $package_price = $row["round_package_price"];
                $unit_price = $row["round_unit_price"];
                $pieces_price = $row["round_pieces_price"];
                $package_exist = $row['package_exist'];
                $unit_exist = $row['unit_exist'];
                $pieces_exist = $row['pieces_exist'];
                $pieces_exist = $row['pieces_exist'];
                $type = $row['type'];
                $type = $row['type'];
                $customer = '-';

                $voucher = 'လက်လီ';
                $buy_type = 'လက်ငင်း';
                $tra_id = $tra_id_data->format('YmdHis') . '' . $rn;
                $today_date = date('Y-m-d');
                $exp_debt = date('Y-m-d');
                $total = $pieces_price;
                $discount = '0';
                $rate = '1';


                $b_id = $browserId;
                $sql = "SELECT * FROM " . $user_database . " WHERE browser_id='$b_id'";
                $result = $connection->query($sql);
                if ($result && $result->num_rows > 0) {
                    while ($row = $result->fetch_assoc()) {

                        $user_id = $row['user_name_LL'];
                        $user_name = $row['user_name'];


                        $is_stock_sufficient = true; // Flag to check stock availability

                        // Check stock based on type
                        if ($typeData == "ဖာ") {
                            if (
                                $package_exist < 1 || $package_exist < $qtyData
                            ) {
                                echo "<script>alert('လက်ကျန်ဖာ မလုံလောက်ပါ');</script>";
                            
                                $is_stock_sufficient = false;
                            } else {
                                $total_f = $package_price * $qtyData;
                                $price = $package_price;
                            }
                        } else if ($typeData == "ကဒ်") {
                            if (
                                $unit_exist < 1 || $unit_exist < $qtyData
                            ) {
                                echo "<script>alert('လက်ကျန်ကဒ် မလုံလောက်ပါ');</script>";
                              
                                $is_stock_sufficient = false;
                            } else {
                                $total_f = $unit_price * $qtyData;
                                $price = $unit_price;
                            }
                        } else if ($typeData == "ဗူး/ခု") {
                            if ($pieces_exist < 1 || $pieces_exist < $qtyData) {
                                echo "<script>alert('လက်ကျန်ဗူး မလုံလောက်ပါ');</script>";
      
                                $is_stock_sufficient = false;
                            } else {
                                $total_f = $pieces_price * $qtyData;
                                $price = $pieces_price;
                            }
                        }

                        // Proceed only if stock is sufficient
                        if ($is_stock_sufficient) {
                            // Insert data into user table
                            $insert_sql_user = "INSERT INTO " . $user_id . "(date, barcode, product_name, price, qty, total, tra_id, customer, type, exp_debt, voucher, discount, buy_type, seller, banking, rate)
                                        VALUES ('$today_date', '$barcode', '$product_name', '$price', '$qtyData', '$total_f', '$tra_id', '$customer', '$typeData', '$exp_debt', '$voucher', '$discount', '$buy_type', '$user_name', '$bankingData', '$rate')";
                            mysqli_query($connection, $insert_sql_user);

                            // Insert data into sell data table
                            $insert_sql_sell = "INSERT INTO " . $sell_data . "(date, barcode, product_name,item_type, price, qty, total, tra_id, customer, type, exp_debt, voucher, discount, buy_type, seller, banking, rate)
                                        VALUES ('$today_date', '$barcode', '$product_name','$type', '$price', '$qtyData', '$total_f', '$tra_id', '$customer', '$typeData', '$exp_debt', '$voucher', '$discount', '$buy_type', '$user_name', '$bankingData', '$rate')";
                            mysqli_query($connection, $insert_sql_sell);

                            // Update product exist
                            $query = "UPDATE $product p
                            LEFT JOIN (SELECT product_name, 
                                                SUM(CASE WHEN type='ဗူး/ခု' THEN qty ELSE 0 END) AS pieces_sell,
                                                SUM(CASE WHEN type='ကဒ်' THEN qty ELSE 0 END) AS unit_sell,
                                                SUM(CASE WHEN type='ဖာ' THEN qty ELSE 0 END) AS package_sell
                                        FROM $sell_data 
                                        WHERE product_name='$product_name'
                                        GROUP BY product_name) s 
                            ON p.product_name = s.product_name
                            SET p.pieces_sell = COALESCE(s.pieces_sell, 0),
                                p.unit_sell = COALESCE(s.unit_sell, 0),
                                p.package_sell = COALESCE(s.package_sell, 0)";
                            $connection->query($query);

                            // Final update query
                            $final_update_query = "UPDATE $product SET 
                                        package_exist = (package_remain+package_trans) - (package_sell + package_damage + unit_change),
                                        unit_exist = (unit_remain+unit_trans) - (unit_sell + unit_damage) + (unit_change * unit) - pieces_change,
                                        pieces_exist = (pieces_remain+pieces_trans) - (pieces_sell + pieces_damage) + (pieces_change * pieces)
                                        WHERE product_name='$product_name'";
                            if (!$connection->query($final_update_query)) {
                                $connection->rollback();
                                die("ERROR: Query failed. " . $connection->error);
                            }

                            echo "<script>window.location.href = 'sell_ll.php';</script>";
                        }
                    }
                }
            }
        }
    }
}




if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $tra_id = isset($_POST['tra_id']) ? $_POST['tra_id'] : null;
    $action = isset($_POST['action']) ? $_POST['action'] : null;

    switch ($action) {
        case 'info':
            $sql = "SELECT * FROM " . $sell_data . " WHERE tra_id = '$tra_id'";
            $result = $connection->query($sql);

            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $barcode = $row['barcode'];

                // Second query to get the product details
                $sql = "SELECT * FROM " . $product . " WHERE barcode = '$barcode' or barcode_1='$barcode'";
                $result = $connection->query($sql);
                if ($result->num_rows > 0) {
                    $row = $result->fetch_assoc();
                    $imageData = $row['image'];

                    echo ' 
                <div class="modal fade" id="infoModal" tabindex="-1" aria-labelledby="infoModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header bg-info text-white">
                                <h5 class="modal-title" id="infoModalLabel">' . htmlspecialchars($row["product_name"]) . '</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="refreshPage()">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <div class="text-center">
                                    <img src="data:image/jpeg;base64,' . base64_encode($imageData) . '" class="img-fluid mb-3" alt="Sample Image" style="margin-left:auto;margin-right:auto;">
                                </div>
                                <p class="card-text" style="font-size:15px">ပစ္စည်းအမည်: <a style="color:white">' . htmlspecialchars($row["product_name"]) . '</a></p>
                                <p class="card-text" style="font-size:15px">code နံပါတ်: <a style="color:white">' . htmlspecialchars($row["barcode"]) . '</a></p>
                                <p class="card-text" style="font-size:15px">အမျိုးစား: <a style="color:white">' . htmlspecialchars($row["type"]) . '</a></p>
                                <p class="card-text" style="font-size:15px">ရောင်းဈေးဖာ: <a style="color:white">' . htmlspecialchars($row["round_package_price"]) . '&nbsp' . htmlspecialchars($row["currency_buy"]) . '</a></p>
                                <p class="card-text" style="font-size:15px">ရောင်းဈေးကဒ်: <a style="color:white">' . htmlspecialchars($row["round_unit_price"]) . '&nbsp' . htmlspecialchars($row["currency_buy"]) . '</a></p>
                                <p class="card-text" style="font-size:15px">ရောင်းဈေးဘူး: <a style="color:white">' . htmlspecialchars($row["round_pieces_price"]) . '&nbsp' . htmlspecialchars($row["currency_buy"]) . '</a></p>
                                <p class="card-text" style="font-size:15px">လက်ကျန်ဖာ: <a style="color:white">' . htmlspecialchars($row["package_exist"]) . '</a></p>
                                <p class="card-text" style="font-size:15px">လက်ကျန်ကဒ်: <a style="color:white">' . htmlspecialchars($row["unit_exist"]) . '</a></p>
                                <p class="card-text" style="font-size:15px">လက်ကျန်ဘူး: <a style="color:white">' . htmlspecialchars($row["pieces_exist"]) . '</a></p>
                                <a href="#" class="btn btn-primary">Learn More</a>
                            </div>
                        </div>
                    </div>
                </div>';
                } else {
                    echo "Product not found.";
                }
            } else {
                echo "Transaction not found.";
            }



            break;

        case 'upload':

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

                    $sql = "SELECT * FROM " . $sell_data . " WHERE tra_id = '$tra_id'";
                    $result = $connection->query($sql);
                    if ($result->num_rows > 0) {
                        $row = $result->fetch_assoc();
                        $barcode = $row['barcode'];
                        $type = $row['type'];
                        $product_name = $row['product_name'];

                        if ($type == "ဗူး/ခု") {
                            $sql = "SELECT * FROM " . $product . " WHERE product_name = '$product_name'";
                            $result = $connection->query($sql);
                            if ($result->num_rows > 0) {
                                $row = $result->fetch_assoc();

                                $pieces_exist = $row['pieces_exist'];
                                $price = $row['round_pieces_price'];
                                $type = 'ဗူး/ခု';

                                $total_f = $price * $pieces_exist;
                                echo $total_f;

                                $query = "UPDATE " . $user_id . "  set price='$price',qty='$pieces_exist', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                if (!$connection->query($query)) {
                                    die("ERROR: Query failed. " . $connection->error);
                                }

                                $query = "UPDATE " . $sell_data . " set price='$price',qty='$pieces_exist', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                if (!$connection->query($query)) {
                                    die("ERROR: Query failed. " . $connection->error);
                                }
                            }
                        } else if ($type == "ကဒ်") {

                            $sql = "SELECT * FROM " . $product . " WHERE product_name = '$product_name'";
                            $result = $connection->query($sql);
                            if ($result->num_rows > 0) {
                                $row = $result->fetch_assoc();

                                $unit_exist = $row['unit_exist'];
                                $price = $row['round_unit_price'];
                                $type = 'ကဒ်';

                                $total_f = $price * $unit_exist;
                                echo $total_f;

                                $query = "UPDATE " . $user_id . "  set price='$price',qty='$unit_exist', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                if (!$connection->query($query)) {
                                    die("ERROR: Query failed. " . $connection->error);
                                }

                                $query = "UPDATE " . $sell_data . " set price='$price',qty='$unit_exist', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                if (!$connection->query($query)) {
                                    die("ERROR: Query failed. " . $connection->error);
                                }
                            }
                        } else if ($type == "ဖာ") {

                            $sql = "SELECT * FROM " . $product . " WHERE product_name = '$product_name'";
                            $result = $connection->query($sql);
                            if ($result->num_rows > 0) {
                                $row = $result->fetch_assoc();

                                $package_exist = $row['package_exist'];
                                $price = $row['round_package_price'];
                                $type = 'ဖာ';

                                $total_f = $price * $package_exist;
                                echo $total_f;

                                $query = "UPDATE " . $user_id . "  set price='$price',qty='$package_exist', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                if (!$connection->query($query)) {
                                    die("ERROR: Query failed. " . $connection->error);
                                }

                                $query = "UPDATE " . $sell_data . " set price='$price',qty='$package_exist', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                if (!$connection->query($query)) {
                                    die("ERROR: Query failed. " . $connection->error);
                                }
                            }
                        }
                        echo "<script>window.location.href = 'sell_ll.php';</script>";
                    }
                }
            }



            break;


        case 'delete':


            $sql = "SELECT * FROM " . $user_database . " WHERE browser_id='$b_id'";
            $result = $connection->query($sql);
            if ($result && $result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    //$user_id = $row['user_name_LL_LL'];
                    $user_id = $row['user_name_LL'];

                    $query = "DELETE FROM " . $user_id . " WHERE tra_id = '$tra_id'";
                    if ($connection->query($query)) {
                    } else {
                    }

                    $query = "DELETE FROM " . $sell_data . " WHERE tra_id = '$tra_id'";
                    if ($connection->query($query)) {
                    } else {
                    }
                }
            }

            $query = "UPDATE $product p
                            LEFT JOIN (SELECT product_name, 
                                                SUM(CASE WHEN type='ဗူး/ခု' THEN qty ELSE 0 END) AS pieces_sell,
                                                SUM(CASE WHEN type='ကဒ်' THEN qty ELSE 0 END) AS unit_sell,
                                                SUM(CASE WHEN type='ဖာ' THEN qty ELSE 0 END) AS package_sell
                                        FROM $sell_data 
                                        GROUP BY product_name) s 
                            ON p.product_name = s.product_name
                            SET p.pieces_sell = COALESCE(s.pieces_sell, 0),
                                p.unit_sell = COALESCE(s.unit_sell, 0),
                                p.package_sell = COALESCE(s.package_sell, 0)";
                            $connection->query($query);

                            // Final update query
                            $final_update_query = "UPDATE $product SET 
                                        package_exist = (package_remain+package_trans) - (package_sell + package_damage + unit_change),
                                        unit_exist = (unit_remain+unit_trans) - (unit_sell + unit_damage) + (unit_change * unit) - pieces_change,
                                        pieces_exist = (pieces_remain+pieces_trans) - (pieces_sell + pieces_damage) + (pieces_change * pieces)
                                        WHERE product_name='$product_name'";
                            if (!$connection->query($final_update_query)) {
                                $connection->rollback();
                                die("ERROR: Query failed. " . $connection->error);
                            }
            echo "<script>window.location.href = 'sell_ll.php';</script>";
            break;

        default:
    }
} else {
}


?>

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

<style>
    video {
        width: 100%;
        height: 200px;

        object-fit: cover;
        /* Ensures the video fills the container */
        display: block;
    }
</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="row">

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

                            <form id="myForm" action="sell_ll.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">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="pwd">အမျိုးစား:</label></th>
                                        <th>
                                            <select name="typeData" id="typeInput" class="form-control">
                                                <option value="ဖာ">ဖာ</option>
                                                <option value="ကဒ်">ကဒ်</option>
                                                <option value="ဗူး/ခု">ဗူး/ခု</option>

                                            </select>
                                        </th>
                                    </tr>


                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi"> အရေတွက်:</label></th>
                                        <th><input type="text" class="form-control" id="qtyInput" name="qtyData" placeholder="" value="1" maxlength="20" oninput="validateNumber(this)"></th>

                                    </tr>

                                    <script>
                                        function validateNumber(input) {
                                            input.value = input.value.replace(/[^0-9]/g, ''); // Only allow digits
                                        }
                                    </script>


                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" class="text-info">banking:</label></th>
                                        <th>
                                            <select name="bankingData" id="bankingInput" 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" class="text-info"> Voucher:</label></th>
                                        <th>
                                            <div style="display:flex;">
                                                <input type="text" class="form-control" name="voucher" id="voucher" placeholder="" value="1" style="width:80%">
                                                <button type="button" name="auto_voucher" id="auto_voucher" class="btn btn-outline-warning" style="margin-left:10px">Auto</button>
                                            </div>
                                        </th>
                                        <!-- <th><button type="button" name="print" id="print" class="btn btn-outline-warning">Print</button></th> -->
                                    </tr>

                                    <?php

                                    // SQL query to fetch the latest record
                                    $sql = "SELECT * FROM " . $sell_data . " WHERE voucher!='လက်ကား' ORDER BY id DESC LIMIT 1";
                                    $result = $connection->query($sql);

                                    if ($result && $result->num_rows > 0) {
                                        $row = $result->fetch_assoc();
                                        $voucherValue = (int)$row['voucher'] + 1;
                                    }

                                    ?>

                                    <script>
                                        document.getElementById('auto_voucher').addEventListener('click', function() {
                                            var voucherValue = <?php echo $voucherValue; ?>;
                                            document.getElementById('voucher').value = voucherValue;
                                        });
                                    </script>



                                </table>

                                <div style="margin-top: 20px; display: flex; justify-content: center;" class="container-fluid">

                                    <table class="table table-borderless">

                                        <tr>
                                            <td scope="col" colspan="3">
                                                <button type="submit" name="add" class="btn btn-outline-warning" style="width:100%" id="addButton">Add</button>
                                            </td>
                                        </tr>

                                        <tr>
                                            <td scope="col"><button style="width:100%" type="button" name="print" id="print" class="btn btn-outline-warning">Print</button></td>
                                            <td scope="col"><button style="width:100%" type="submit" name="save" class="btn btn-outline-danger">Save</button></td>
                                            <td scope="col"><button style="width:100%" type="submit" name="update" class="btn btn-outline-info">Update</button></td>
                                        </tr>



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

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



                                    </table>
                                    <!-- <button type="submit" name="add" class="btn btn-outline-warning" style="margin: 10px;">Print</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> -->



                            <script>
                                const button_print = document.getElementById('print');
                                button_print.addEventListener('click', function() {
                                    window.location.href = 'print_ll.php';
                                });
                            </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" class="text-center align-middle">
                                        <tr>
                                            <th rowspan="2" style="display: none;" scope="col">tra_id</th>
                                            <th rowspan="2" scope="col">info</th>
                                            <th rowspan="2" scope="col">barcode</th>
                                            <th rowspan="2" scope="col">ပစ္စည်းအမည်</th>
                                            <th rowspan="2" scope="col">အမျိုးစား</th>
                                            <th rowspan="2" scope="col">ရောင်းဈေး</th>
                                            <th rowspan="2" scope="col">လျော့ဈေး</th>
                                            <th rowspan="2" scope="col">ပမာဏ</th>
                                            <th rowspan="2" scope="col">စုစုပေါင်း</th>
                                            <th rowspan="2" scope="col">ဘဏ်</th>
                                            <th rowspan="2" scope="col" style="display: none;">ကဒ်နံပါတ်</th>
                                            <th rowspan="2" scope="col">Delete</th>
                                            <th rowspan="2" scope="col">အားလုံး</th>
                                            <th rowspan="2" scope="col">Voucher</th>
                                        </tr>
                                    </thead>
                                    <tbody>


                                        <?php

                                        $b_id = $browserId;

                                        $sql = "SELECT * FROM " . $user_database . " WHERE browser_id='$b_id'";
                                        $result = $connection->query($sql);
                                        if ($result && $result->num_rows > 0) {
                                            while ($row = $result->fetch_assoc()) {

                                                $seller = $row['user_name_LL'];
                                                $user_name = $row['user_name'];

                                                $sql = "SELECT * FROM " . $seller . " WHERE seller='" . $user_name . "' order by id desc";
                                                $result = mysqli_query($connection, $sql);
                                                if ($result) {
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        echo '<tr>
                                            <td contenteditable="true" style="display: none;">' . htmlspecialchars($row['tra_id']) . '</td>       
                                            <td><button type="button" class="btn btn-success" data-action="info" name="info" data-toggle="modal" data-target="#infoModal">Info</button></td>     
                                            <td contenteditable="true">' . htmlspecialchars($row['barcode']) . '</td>
                                            <th contenteditable="true" scope="row">' . htmlspecialchars($row['product_name']) . '</td>';

                                                        echo '<td contenteditable="true">
                                            <select id="cars" contenteditable="true">
                                                <option value="' . $row['type'] . '">' . $row['type'] . '</option>
                                                <option value="ဗူး/ခု">ဗူး/ခု</option>
                                                <option value="ကဒ်">ကဒ်</option>
                                                <option value="ဖာ">ဖာ</option>
                                            </select></td>';

                                                        echo '<td contenteditable="true">' . number_format(htmlspecialchars($row['price'] / $row['rate']), 0) . '</td> 
                                             <td contenteditable="true">' . number_format(htmlspecialchars($row['discount'] / $row['rate']), 0) . '</td>           
                                            <td contenteditable="true">' . htmlspecialchars($row['qty']) . '</td>   
                                            <td contenteditable="true">' . number_format(htmlspecialchars($row['total'] / $row['rate'])) . '</td>                                                                                        
                                            <td contenteditable="true">' . (htmlspecialchars($row['banking'])) . '</td>                                                                                        
                                            <td contenteditable="true" style="display: none;">' . htmlspecialchars($row['customer']) . '</td>                                                                                        
                                            <td><button type="submit" class="btn btn-danger" data-action="delete">Delete</button></td>    
                                            <td><button type="submit" class="btn btn-warning" data-action="upload">အားလုံး</button></td>                            
                                            <td contenteditable="true">' . htmlspecialchars($row['voucher']) . '</td>                             
                                            </tr>';
                                                    }
                                                }
                                            }
                                            $query = "SELECT sum(total/rate) as total_sum,banking FROM `$seller` WHERE seller='" . $user_name . "'";
                                            $result = $connection->query($query);
                                            if ($result->num_rows > 0) {
                                                $row = $result->fetch_assoc();
                                                $total = $row['total_sum'];
                                                $payment_data = $row['banking'];

                                                $sql = "SELECT currency FROM " . $banking . " WHERE type='$payment_data'";
                                                $result = $connection->query($sql);
                                                if ($result && $result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        $currency = $row['currency'];

                                                        echo '
                                                <tr>
                                                <td colspan=6 style="text-align:center;">Total</td>
                                                <td colspan=2><b>' . number_format($total) . ' ' . $currency . ' </br></td>
                                                </tr>
                                                ';
                                                    }
                                                }
                                            }
                                        }



                                        mysqli_free_result($result);

                                        ?>
                                    </tbody>
                                </table>

                                <form id="actionForm" method="POST" action="sell_ll.php" style="display:none;">
                                    <input type="hidden" name="tra_id" id="formId">
                                    <input type="hidden" name="action" id="formAction">
                                </form>

                                <!-- Button on Table -->
                                <script>
                                    document.addEventListener('DOMContentLoaded', function() {
                                        document.getElementById('dataTable').addEventListener('click', function(event) {
                                            if (event.target.tagName === 'BUTTON') {
                                                const action = event.target.getAttribute('data-action');
                                                const row = event.target.closest('tr');
                                                const tra_id = row.cells[0].innerText;

                                                // Create a FormData object and append the necessary data
                                                const formData = new FormData();
                                                formData.append('tra_id', tra_id);
                                                formData.append('action', action);

                                                // Send the form data using Fetch API
                                                fetch('sell_ll.php', {
                                                        method: 'POST',
                                                        body: formData
                                                    })
                                                    .then(response => response.text())
                                                    .then(data => {
                                                        if (action === 'delete') {
                                                            // Refresh the page if the delete action is performed
                                                            location.reload();
                                                        } else {
                                                            // Insert the returned HTML into a container element
                                                            const modalContainer = document.createElement('div');
                                                            modalContainer.innerHTML = data;
                                                            document.body.appendChild(modalContainer);

                                                            // Display the modal
                                                            const modal = new bootstrap.Modal(modalContainer.querySelector('.modal'));
                                                            modal.show();

                                                            // Add event listener to refresh the page when the modal is hidden
                                                            modalContainer.querySelector('.modal').addEventListener('hidden.bs.modal', function() {
                                                                location.reload();
                                                            });
                                                        }
                                                    })
                                                    .catch(error => {
                                                        console.error('Error:', error);
                                                    });
                                            }
                                        });
                                    });
                                </script>

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




                                <!-- ရောင်းဈေးကို check ပြန်လုပ်ရန် -->
                                <!-- Edit Data by click -->
                                <!-- Check Back -->
                                <?php
                                if ($_SERVER["REQUEST_METHOD"] == "POST") {
                                    $data = json_decode(file_get_contents('php://input'), true);

                                    // Assuming 'no' is the primary key for your product table
                                    if (isset($data['tra_id'])) {
                                        // Escape incoming data
                        $tra_id = $connection->real_escape_string($data['tra_id']);
                        $barcode = $connection->real_escape_string($data['barcode']);
                        $product_name = $connection->real_escape_string($data['ပစ္စည်းအမည်']);
                        $type = $connection->real_escape_string($data['အမျိုးစား']);
                        $qty = $connection->real_escape_string($data['ပမာဏ']);
                        $discount_1 = $connection->real_escape_string($data['လျော့ဈေး']);
                        $banking_data = $connection->real_escape_string($data['ဘဏ်']);
                        $price = $connection->real_escape_string($data['ရောင်းဈေး']);
                        
                        // Retrieve currency type from the banking table
                        $sql = "SELECT currency FROM ".$banking." WHERE type='$banking_data'";
                        $result = $connection->query($sql);
                        if ($result && $result->num_rows > 0) {
                            $currency_data = $result->fetch_assoc();
                            $currency = $currency_data['currency'];
                            
                            // Retrieve rates for each currency type from the rate table
                            $sql = "SELECT baht, yuan, dollar FROM ".$rate;
                            $result = $connection->query($sql);
                            if ($result && $result->num_rows > 0) {
                                $rate_data = $result->fetch_assoc();
                                $baht = $rate_data['baht'];
                                $yuan = $rate_data['yuan'];
                                $dollar = $rate_data['dollar'];
                        
                                // Perform discount calculation based on currency type
                                switch ($currency) {
                                    case 'kyat':
                                        $discount = $discount_1 * 1;
                                
                                        break;
                                    case 'baht':
                                        $discount = $discount_1 * $baht;
                                        break;
                                    case 'yuan':
                                        $discount = $discount_1 * $yuan;
                                        break;
                                    case 'dollar':
                                        $discount = $discount_1 * $dollar;
                                        break;
                                    default:
                                        $discount = 0; // Handle any unexpected currency type
                                        break;
                                }
                            }
                        }
                                
                                        // Remove commas
                                        $buy_data_1 = str_replace(",", "", $buy_data);
                        
                                        // Convert to integer or float
                                        $buy = intval($buy_data_1);
                                    
                                        //update barcode,name.....
                                        $sql = "SELECT * FROM ".$user_database." WHERE browser_id='$b_id'";
                                        $result = $connection->query($sql);
                                        if ($result && $result->num_rows > 0) {
                                        while ($row = $result->fetch_assoc()) {
                                            $user_id = $row['user_name_LL']; //Database
                        
                                                $sql = "SELECT * FROM ".$product." WHERE product_name='$product_name'";
                                                $result = $connection->query($sql);
                        
                                                if ($result && $result->num_rows > 0) {
                                                    $row = $result->fetch_assoc();
                                                    
                                                    if ($type == 'ဗူး/ခု') {
                                                        $price = $row['round_pieces_price'];
                                                        $f_price = $price - $discount;
                                                        $total_f = $f_price * $qty;
                        
                                                        $sql = "SELECT package_exist,unit_exist,pieces_exist FROM ".$product." WHERE product_name='$product_name'";
                                                        $result = $connection->query($sql);
                                                        if ($result && $result->num_rows > 0) {
                                                        while ($row = $result->fetch_assoc()) {
                                                        $pieces_exist = $row['pieces_exist'];
                                                        if ($pieces_exist < $qty){
                                                            echo '<script>alert("Item is not Enough")</script>';
                                                        }
                        
                                                        else{
                                                            $query = "UPDATE ".$user_id."  set discount='$discount',price='$price',qty='$qty', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                                            if (!$connection->query($query)) {
                                                                die("ERROR: Query failed. " . $connection->error);
                                                            }
                                                          
                                                            $query = "UPDATE ".$sell_data." set discount='$discount',price='$price',qty='$qty', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                                            if (!$connection->query($query)) {
                                                                die("ERROR: Query failed. " . $connection->error);
                                                            }
                                                     
                                                         
                                                        }
                                                        }
                                                    }
                        
                                                    } elseif ($type == 'ကဒ်') {
                                                        $price = $row['round_unit_price'];
                                        
                                                        $f_price = $price - $discount;
                                                        $total_f = $f_price * $qty;
                        
                                                        $sql = "SELECT package_exist,unit_exist,pieces_exist FROM ".$product." WHERE product_name='$product_name'";
                                                        $result = $connection->query($sql);
                                                        if ($result && $result->num_rows > 0) {
                                                        while ($row = $result->fetch_assoc()) {
                        
                                                        $unit_exist = $row['unit_exist'];
                                                        if ($unit_exist < $qty){
                                                            echo '<script>alert("Item is not Enough")</script>';
                                                        }
                                                        else{
                                                            $query = "UPDATE ".$user_id."  set discount='$discount',price='$price',qty='$qty', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                                            if (!$connection->query($query)) {
                                                                die("ERROR: Query failed. " . $connection->error);
                                                            }
                        
                                                            $query = "UPDATE ".$sell_data." set discount='$discount',price='$price',qty='$qty', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                                            if (!$connection->query($query)) {
                                                                die("ERROR: Query failed. " . $connection->error);
                                                            }
                                                    
                                                          
                                                        }
                                                        }
                                                    }
                        
                        
                                                    } elseif ($type == 'ဖာ') {
                                                        $price = $row['round_package_price'];
                        
                                                        $f_price = $price - $discount;
                                                        $total_f = $f_price * $qty;
                        
                                                        $sql = "SELECT package_exist,unit_exist,pieces_exist FROM ".$product." WHERE product_name='$product_name'";
                                                        $result = $connection->query($sql);
                                                        if ($result && $result->num_rows > 0) {
                                                        while ($row = $result->fetch_assoc()) {
                        
                                                        $package_exist = $row['package_exist'];
                                                        if ($package_exist < $qty){
                                                            echo '<script>alert("Item is not Enough")</script>';
                                                        }
                                                        else{
                                                            $query = "UPDATE ".$user_id."  set discount='$discount',price='$price',qty='$qty', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                                            if (!$connection->query($query)) {
                                                                die("ERROR: Query failed. " . $connection->error);
                                                            }
                        
                                                            $query = "UPDATE ".$sell_data." set discount='$discount',price='$price',qty='$qty', type='$type', total='$total_f' WHERE tra_id='$tra_id'";
                                                            if (!$connection->query($query)) {
                                                                die("ERROR: Query failed. " . $connection->error);
                                                            }
                                                           
                                                        }
                                                        }
                                                    }
                                                    }  

                                                    $query = "UPDATE $product p
                                                    LEFT JOIN (SELECT product_name, 
                                                                        SUM(CASE WHEN type='ဗူး/ခု' THEN qty ELSE 0 END) AS pieces_sell,
                                                                        SUM(CASE WHEN type='ကဒ်' THEN qty ELSE 0 END) AS unit_sell,
                                                                        SUM(CASE WHEN type='ဖာ' THEN qty ELSE 0 END) AS package_sell
                                                                FROM $sell_data 
                                                                WHERE product_name='$product_name'
                                                                GROUP BY product_name) s 
                                                    ON p.product_name = s.product_name
                                                    SET p.pieces_sell = COALESCE(s.pieces_sell, 0),
                                                        p.unit_sell = COALESCE(s.unit_sell, 0),
                                                        p.package_sell = COALESCE(s.package_sell, 0)";
                                                    $connection->query($query);
                        
                                                    // Final update query
                                                    $final_update_query = "UPDATE $product SET 
                                        package_exist = (package_remain+package_trans) - (package_sell + package_damage + unit_change),
                                        unit_exist = (unit_remain+unit_trans) - (unit_sell + unit_damage) + (unit_change * unit) - pieces_change,
                                        pieces_exist = (pieces_remain+pieces_trans) - (pieces_sell + pieces_damage) + (pieces_change * pieces)
                                        WHERE product_name='$product_name'";
                            if (!$connection->query($final_update_query)) {
                                $connection->rollback();
                                die("ERROR: Query failed. " . $connection->error);
                            }

                                                    echo "<script>window.location.href = 'sell_ll.php';</script>";
                        


                                                }  
                                            }
                                        }
                        
                                       
                                    } else {
                                        // echo json_encode(['status' => 'error', 'message' => 'Invalid data format.']);
                                    }
                                    
                                    }
                                   
                                
                                ?>
                                <!-- Edit Table by Click on Cell -->
                                <script>
                                    function getFlattenedHeaders(headerRow) {
                                        const headers = [];
                                        let colIndex = 0;

                                        for (let i = 0; i < headerRow.cells.length; i++) {
                                            const cell = headerRow.cells[i];
                                            const colspan = cell.colSpan || 1;
                                            const headerText = cell.textContent.trim();

                                            for (let j = 0; j < colspan; j++) {
                                                headers[colIndex] = headerText;
                                                colIndex++;
                                            }
                                        }

                                        console.log('Flattened Headers:', headers);
                                        return headers;
                                    }

                                    function saveChangesForRow(row) {
                                        const data = {};
                                        console.log('Row being processed:', row);

                                        const headerRow = document.getElementById('dataTable').rows[0];
                                        const headers = getFlattenedHeaders(headerRow);

                                        for (let j = 0; j < row.cells.length; j++) {
                                            const cell = row.cells[j];

                                            if (j >= headers.length) {
                                                console.warn(`Skipping cell ${j} as it exceeds header length`);
                                                continue; // Skip if there are more cells in the row than in the headers
                                            }

                                            const headerText = headers[j];
                                            console.log(`Processing cell ${j}: Header=${headerText}, Cell=`, cell);

                                            if (cell && cell.hasAttribute('contenteditable')) {
                                                data[headerText] = cell.textContent.trim();
                                            }

                                            // Handle select dropdowns separately
                                            if (cell.querySelector('select')) {
                                                data[headerText] = cell.querySelector('select').value;
                                            }
                                        }

                                        console.log('Data to be sent:', data);

                                        const xhr = new XMLHttpRequest();
                                        xhr.open('POST', 'sell_ll.php', true);
                                        xhr.setRequestHeader('Content-Type', 'application/json');
                                        xhr.onreadystatechange = function() {
                                            if (xhr.readyState === XMLHttpRequest.DONE) {
                                                if (xhr.status === 200) {
                                                    // console.log('Data updated successfully!');
                                                } else {
                                                    // alert('Error updating data. Please try again!');
                                                }
                                            }
                                        };
                                        xhr.send(JSON.stringify(data));
                                    }

                                    const editableCells = document.querySelectorAll('#dataTable td[contenteditable="true"]');
                                    editableCells.forEach(cell => {
                                        cell.addEventListener('input', function() {
                                            saveChangesForRow(this.parentElement); // this.parentElement refers to the row
                                        });
                                    });

                                    const dropdowns = document.querySelectorAll('#dataTable select');
                                    dropdowns.forEach(dropdown => {
                                        dropdown.addEventListener('change', function() {
                                            saveChangesForRow(this.closest('tr')); // 'closest' gets the nearest parent row element
                                        });
                                    });
                                </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>



    <div id="output"></div>


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