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

    <!-- Load only the full version of jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <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 "login_check.php";

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $tra_id = isset($_POST['tra_id']) ? $_POST['tra_id'] : null;
    $action = isset($_POST['action']) ? $_POST['action'] : null;

    if ($action === 'delete' && $tra_id) {
        $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'];

                // Delete from user-specific table
                $query = "DELETE FROM " . $user_id . " WHERE tra_id = '$tra_id'";
                $connection->query($query);

                // Delete from sell_data table
                $query = "DELETE FROM " . $sell_data . " WHERE tra_id = '$tra_id'";
                $connection->query($query);
            }
        }
    }

    if ($action === 'info' && $tra_id) {

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




            // Second query to get the product details
            $sql = "SELECT * FROM " . $product . " WHERE product_name = '$product_name'";
            $result = $connection->query($sql);

            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                $package = $row['package_exist'];
                $unit = $row['unit_exist'];
                $pieces = $row['pieces_exist'];

                $package_price = $row['round_package_price'];
                $unit_price = $row['round_unit_price'];
                $pieces_price = $row['round_pieces_price'];

                echo "<script>alert('$package ဖာ\\n$unit ကဒ်\\n$pieces ဗူး/ကဒ်\\n$package_price ဖာဈေး\\n$unit_price ကဒ်ဈေး\\n$pieces_price ဗူးဈေး');</script>";


                // echo "<script>alert('
                // လက်ကျန်ဖာ-$package<br>
                // လက်ကျန်ကဒ်-$unit<br>
                // လက်ကျန်ဗူး-$pieces<br>

                // ')</script>";


            } else {
                echo "Product not found.";
            }
        } else {
            echo "Transaction not found.";
        }
    }
}


?>



<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"> -->
                            <form id="myForm" style="margin-top:20px;margin-left:20px">
                                <table style="border:none;">

                                    <tr style="height: 50px;">
                                        <th> <label for="pwd" alt="hi">Barcode:</label></th>
                                        <th>
                                            <div style="display:flex;">
                                                <input type="text" class="form-control" name="barcode" id="barcodeInput" placeholder="" style="width:80%" autofocus>
                                                <button type="button" id="start-scan-btn" class="btn btn-outline-warning" style="margin-left:10px">Scan</button>
                                            </div>
                                        </th>
                                        <!-- <th><button type="button" name="print" id="print" class="btn btn-outline-warning">Print</button></th> -->
                                    </tr>

                                    <script>
                                        document.addEventListener('DOMContentLoaded', () => {
                                            const video = document.getElementById('barcode-scanner');
                                            const barcodeInput = document.getElementById('barcodeInput');
                                            const startScanButton = document.getElementById('start-scan-btn');
                                            let stream = null; // To store the camera stream

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

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

                                            async function detectBarcode() {
                                                const barcodeDetector = new BarcodeDetector();

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

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

                                    <?php
                                    $data = [];

                                    // SQL query to fetch product names
                                    $sql = "SELECT product_name FROM " . $product . "";
                                    $result_inner = $connection->query($sql);

                                    // Check if the query returned any results
                                    if ($result_inner && $result_inner->num_rows > 0) {
                                        while ($row_inner = $result_inner->fetch_assoc()) {
                                            // Append each product name to the $data array
                                            $data[] = $row_inner['product_name'];
                                        }
                                    }

                                    // Convert PHP array to a JSON array for use in JavaScript
                                    $jsonData = json_encode($data);
                                    ?>

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

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

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

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

                                    <tr style="height: 50px;">
                                        <th> <label for="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" class="btn btn-outline-warning" style="width:100%" id="submitBtn">Add</button>
                                            </td>
                                        </tr>

                                        <tr>
                                            <td scope="col"><button style="width:100%" type="button" name="print" id="print" class="btn btn-outline-warning" onclick="window.location.href='print_ll.php'">Print</button></td>
                                            <td scope="col"><button style="width:100%" type="button" name="save" class="btn btn-outline-danger" id="saveBtn">Save</button></td>
                                            <td scope="col"><button style="width:100%" type="submit" name="update" class="btn btn-outline-info" id="updateBtn">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('submitBtn').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>
                            <div id="result"></div>

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

                                <div id="result"></div>
                                <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>
                                            <th rowspan="2" scope="col">rate</th>
                                        </tr>
                                    </thead>
                                    <tbody id="tableBody">
                                        <!-- Data will be populated here -->
                                    </tbody>
                                </table>

                                <script>
    function loadTableData() {
        $.ajax({
            url: 'sell_ll_table.php', // PHP script for fetching table data
            type: 'GET',
            success: function(data) {
                $('#dataTable tbody').html(data); // Update table body
                enableEditableCells(); // Rebind editable cell functionality
            },
            error: function() {
                alert('Failed to load table data. Please try again.');
            }
        });
    }

    function enableEditableCells() {
        $('#dataTable').off('blur', '[contenteditable="true"]'); // Remove previous event bindings
        $('#dataTable').on('blur', '[contenteditable="true"]', function() {
            const cell = $(this);
            const columnName = cell.data('column');
            let value;

            if (cell.is('select')) {
                value = cell.val(); // Get the selected option value
            } else {
                value = cell.text().trim(); // Get text value for other cells
            }

            const rowId = cell.closest('tr').find('[name="tra_id"]').val();

            // Update via AJAX
            $.ajax({
                url: 'sell_ll_update_cell.php',
                type: 'POST',
                data: {
                    column: columnName,
                    value: value,
                    id: rowId
                },
                success: function(response) {
                    console.log(response);
                    loadTableData(); // Reload table after successful update
                },
                error: function() {
                    alert('Failed to update. Please try again.');
                }
            });
        });
    }

    $(document).ready(function() {
        // Load the table when the page is ready
        loadTableData();

        // Handle "Submit" button click
        $('#myForm').on('submit', function(e) {
            e.preventDefault(); // Prevent form submission

            $.ajax({
                url: 'sell_ll_add.php',
                type: 'POST',
                data: $(this).serialize(),
                success: function(response) {
                    $('#result').html(response);
                    $('#myForm')[0].reset(); // Clear form fields
                    loadTableData(); // Refresh table data
                },
                error: function() {
                    alert('Failed to add entry. Please try again.');
                }
            });
        });

        // Handle "Save" button click
        $('#saveBtn').on('click', function() {
            $.ajax({
                url: 'sell_ll_save.php',
                type: 'POST',
                data: $('#myForm').serialize(),
                success: function(response) {
                    $('#result').html(response);
                    $('#myForm')[0].reset(); // Clear form fields
                    loadTableData(); // Refresh table data
                },
                error: function() {
                    alert('Failed to save data. Please try again.');
                }
            });
        });

        // Handle "Update" button click
        $('#updateBtn').on('click', function() {
            $.ajax({
                url: 'sell_ll_update.php',
                type: 'POST',
                data: $('#myForm').serialize(),
                success: function(response) {
                    $('#result').html(response);
                    $('#myForm')[0].reset(); // Clear form fields
                    loadTableData(); // Refresh table data
                },
                error: function() {
                    alert('Failed to update data. Please try again.');
                }
            });
        });
    });
</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>



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