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

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

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

</style>

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

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


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

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


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



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

//     $name = $_POST['user_name'];
//     $password = $_POST['password'];
//     $sell_lk = $_POST['sell_lk'];
//     $sell_view = $_POST['sell_view'];
//     $product = $_POST['product'];
//     $product_buy = $_POST['product_buy'];
//     $customer = $_POST['customer'];
//     $bank = $_POST['bank'];
//     $expense = $_POST['expense'];
//     $staff = $_POST['staff'];
//     $detail = $_POST['detail'];
//     $cargo = $_POST['cargo'];


//     $sql = "SELECT * FROM ".$user_database." where user_name='$name'";
//     $result = $connection->query($sql);
//     if ($result && $result->num_rows > 0) {
//     while ($row = $result->fetch_assoc()) {
//         echo '<script>alert("Already Exist") ;</script>';
//         echo '<script>window.location = "account_user.php";</script>';
//     }

//     }else{
//       $sql = "INSERT INTO ".$user_database." (user_name, user_name_lk, user_name_LL,password, role,browser_id,active,sell_lk,sell_view,s_1,,s_2,s_3,s_4,s_5,s_6,s_7,s_8,s_9,s_10)
//       VALUES ('$name','','$address','$currency','$role','$total_buy','$debt','$pay','$balance','$remain_debt')";

//       if (mysqli_query($connection, $sql)) {
//           header('location:account_user.php');
//           echo '<script>alert("Add New Customer Success") ;</script>';
//           // echo "Insert successful";
//       } else {
//           echo "Error: " . $sql . "
//   " . mysqli_error($connection);
//       }
//       mysqli_close($connection);


//     }
//   }
    

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

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

    switch ($action) {
        case 'info':
            $sql = "SELECT * FROM ".$product." WHERE id = '$id'";
                $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">'.$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">
                                <!-- Dynamically inserted Image -->
                                <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">'.$row["product_name"].'</a></p>
                                        <p class="card-text" style="font-size:15px">code နံပါတ်: <a style="color:white">'.$row["barcode"].'</a></p>
                                        <p class="card-text" style="font-size:15px">အမျိုးစား: <a style="color:white">'.$row["type"].'</a></p>

                                        <p class="card-text" style="font-size:15px">ရောင်းဈေးဖာ: <a style="color:white">'.$row["round_package_price"].'&nbsp'.$row["currency_buy"].'</a></p>
                                        <p class="card-text" style="font-size:15px">ရောင်းဈေးကဒ်: <a style="color:white">'.$row["round_unit_price"].'&nbsp'.$row["currency_buy"].'</a></p>
                                        <p class="card-text" style="font-size:15px">ရောင်းဈေးဘူး: <a style="color:white">'.$row["round_pieces_price"].'&nbsp'.$row["currency_buy"].'</a></p>

                                        <p class="card-text" style="font-size:15px">လက်ကျန်ဖာ: <a style="color:white">'.$row["package_exist"].'</a></p>
                                        <p class="card-text" style="font-size:15px">လက်ကျန်ကဒ်: <a style="color:white">'.$row["unit_exist"].'</a></p>
                                        <p class="card-text" style="font-size:15px">လက်ကျန်ဘူး: <a style="color:white">'.$row["pieces_exist"].'</a></p>

                           
                                        <a href="#" class="btn btn-primary">Learn More</a>
                                    </div>
                                </div>
                                </div>
                            </div>
                            ';
                        } else {
                            echo "Image not found.";
                        }           
                    echo '
                    ';
            
            

            break;

        case 'upload':

            break;


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

        default:
            
    }
} else {
  
}


?>

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


<body>
<div class="wrapper">
    <?php 
    include "database/database.php";
    include "database/data.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">

                   
                
                <!-- Table Element -->
                <div class="col">

                <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 scope="col">no</th>
                            <!-- <th>info</th> -->
                            <th scope="col">user_name</th>
                            <th scope="col">password</th>
                            <th scope="col">active</th>
                            <th scope="col">role</th>
                            <th scope="col">လက်ကား</th>
                            <th scope="col">ရောင်းစာရင်း</th>
                            <th scope="col">ပစ္စည်းစာရင်း</th>
                            <th scope="col">ပစ္စည်းဝယ်စာရင်း</th>
                            <th scope="col">ဖောက်သည်</th>
                            <th scope="col">ဘဏ်</th>
                            <th scope="col">အသုံးစရိတ်</th>
                            <th scope="col">ဝန်ထမ်း</th>
                            <th scope="col">စာရင်းချုပ်</th>
                            <th scope="col">ဂိုဒေါင်</th>
                            <th scope="col">Dashboard</th>

                            </tr>
                        </thead>
                            <tbody>
                                <?php 
                                // $sql = "Select * from ".$user_database." where role != 'admin'";
                                $sql = "Select * from ".$user_database."";
                                $result = mysqli_query($connection, $sql);
                                if ($result) {
                                    while ($row = mysqli_fetch_assoc($result)) {
                                        echo '<tr>
                                        <td contenteditable="true" class="fixed-column">' . htmlspecialchars($row['id']) . '</td>       
                                        <th contenteditable="true" class="fixed-column-2" scope="row">' . htmlspecialchars($row['user_name']) . '</th>
                                        <td contenteditable="true" class="fixed-column-2" >' . htmlspecialchars($row['password']) . '</td>
                                        <td contenteditable="true" class="fixed-column-2" >' . htmlspecialchars($row['active']) . '</td>
                                        <td contenteditable="true" class="fixed-column-2" >' . htmlspecialchars($row['role']) . '</td>
                                        ';

                                        echo '<td contenteditable="true">
                                            <select id="cars" contenteditable="true">
                                                <option value="' . $row['sell_lk'] . '">' . $row['sell_lk'] . '</option>
                                                <option value="ဖွင့်">ဖွင့်</option>
                                                <option value="ပိတ်">ပိတ်</option>
                                   
                                            </select></td>'; 

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['sell_view'] . '">' . $row['sell_view'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>'; 
 

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['s_2'] . '">' . $row['s_2'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>'; 

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['s_3'] . '">' . $row['s_3'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>'; 

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['s_4'] . '">' . $row['s_4'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>'; 

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['s_5'] . '">' . $row['s_5'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>'; 

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['s_6'] . '">' . $row['s_6'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>'; 

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['s_7'] . '">' . $row['s_7'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>'; 

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['s_8'] . '">' . $row['s_8'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>'; 

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['s_9'] . '">' . $row['s_9'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>';      

                                        echo '<td contenteditable="true">
                                        <select id="cars" contenteditable="true">
                                            <option value="' . $row['s_9'] . '">' . $row['s_9'] . '</option>
                                            <option value="ဖွင့်">ဖွင့်</option>
                                            <option value="ပိတ်">ပိတ်</option>
                                        </select></td>';   

                                    }
                                }
                                    mysqli_free_result($result);
                                
                                ?>
                            </tbody>
                        </table>

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

                           

<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 -->
        <?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['no'])) {
                $no = $connection->real_escape_string($data['no']);
                $user_name = $connection->real_escape_string($data['user_name']);
                $password = $connection->real_escape_string($data['password']);
                $active = $connection->real_escape_string($data['active']);
                $sell_lk = $connection->real_escape_string($data['လက်ကား']);
                $sell_view = $connection->real_escape_string($data['ရောင်းစာရင်း']);

                $product = $connection->real_escape_string($data['ပစ္စည်းစာရင်း']);
                $product_buy = $connection->real_escape_string($data['ပစ္စည်းဝယ်စာရင်း']);
                $customer = $connection->real_escape_string($data['ဖောက်သည်']);
                $bank = $connection->real_escape_string($data['ဘဏ်']);
                $expense = $connection->real_escape_string($data['အသုံးစရိတ်']);
                $staff = $connection->real_escape_string($data['ဝန်ထမ်း']);
                $detail = $connection->real_escape_string($data['စာရင်းချုပ်']);
                $cargo = $connection->real_escape_string($data['ဂိုဒေါင်']);
                $dashboard = $connection->real_escape_string($data['Dashboard']);

           
                //update barcode,name.....
                $sql = "UPDATE ".$user_database." SET user_name='$user_name',password='$password',active='$active',sell_lk='$sell_lk',sell_view='$sell_view',
                s_2='$product',s_3='$product_buy',s_4='$customer',s_5='$bank',s_6='$expense',s_7='$staff',s_8='$detail',s_9='$cargo',s_10='$dashboard' WHERE id='$no'";
                //$sql = "UPDATE product SET barcode='$barcode' WHERE id='$no'";
                if ($connection->query($sql) === TRUE) {
                    echo json_encode(['status' => 'success', 'message' => 'Record updated successfully']);
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'Error updating record: ' . $connection->error]);
                }
                    
            
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Invalid data format.']);
            }
            
            }
        ?>
        <script>
            //get colspan data
            
            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', 'account_user.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>
        </main>


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

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

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

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

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


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

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

let barcode = '';
let timeout;

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

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

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

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

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

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

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


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

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

//     include 'database/database.php';

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

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


?> -->


<?php 

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

    return $randomString . $timestamp;
}

?>

    


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

</html>
